Search code examples
iosobjective-cpropertieskey-value-observing

Send Notification When a Property is Changed Using KVO


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.


Solution

  • 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