Send Notification When a Property is Changed Using KVO

后端 未结 3 790
独厮守ぢ
独厮守ぢ 2021-02-19 05:11

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

@property (nonatomic, strong) NSString *myName;

I need to send a notification whe

3条回答
  •  长情又很酷
    2021-02-19 05:32

    In - (void)setMyName:(NSString *)name do this instead

    [self willChangeValueForKey:@"myName"];
    _myName = name;
    [self didChangeValueForKey:@"myName"];
    
    //this generates the KVO's
    

    And where you want to listen (the viewController), there in viewDidLoad add this line:

    [w addObserver:self forKeyPath:@"myName" options:NSKeyValueObservingOptionNew context:nil];

    //By doing this, you register the viewController for listening to KVO.

    and also implement this method:

    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
        if ([[change objectForKey:NSKeyValueChangeNewKey] isEqual:[NSNull null]]) {
            return;
        } else {
            //read the change dictionary, and have fun :)
        }
    }
    

    //this method is invoked, whenever the property's value is changed.

提交回复
热议问题