Send Notification When a Property is Changed Using KVO

Midhun MP picture Midhun MP · Feb 14, 2013 · Viewed 13.5k times · Source

I had a property named myName in my class, like:

@property (nonatomic, strong) NSString *myName;

I need to send a notification when the myName property's value is changed.

Now I'm doing something like:

- (void)setMyName:(NSString *)name
{
  _myName = name;
  [[NSNotificationCenter defaultCenter] postNotificationName:CHANGE_NOTIFICATION object:nil];
}

I know there is something like Key-Value Observing in iOS. But I don't know how to implement it, I read the entire document, but couldn't get a good understanding.

Please help me to understand how to implement the same without using custom setter.

Answer

alex picture alex · Feb 14, 2013

Try this:

MyClass *var = [MyClass new];
[var addObserver:self forKeyPath:@"myName" options:NSKeyValueChangeOldKey context:nil];

and implement

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{

}

this method will be called anytime when myName property changes