Simple KVO example

久未见 提交于 2019-12-03 01:04:07

KVO works with setter and getter and in incNumber you are directly accessing iVar so instead of that use self.number

- (IBAction)incNumber:(id)sender
{
    self.number++;
    NSLog(@"%d", self.number);
}

Rather than:

_number++;

Try:

[self willChangeValueForKey:@"number"];
_number++;
[self didChangeValueForKey:@"number"];

or ever better just:

self.number++

And let the system take care of the willChangeValueForKey: and didChangeValueForKey: methods.

@interface TraineeLocationCell : UIView
@property (strong, nonatomic) NSString *traineeAddress;
@end

@implementation

// in textview delgate method  i am setting traineeAddress string value
- (void)textViewDidEndEditing:(UITextView *)textView
{
    if (textView.text.length >0)
    [self setValue:textView.text forKey:@"traineeAddress"];

}

@end

and in other class where i am using this class

 TraineeLocationCell *locationView;//create object here
 [locationView addObserver:self forKeyPath:@"traineeAddress" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];//observing the key in this class

//this is the delegate method which take care of value is changed or not

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
   if([keyPath isEqualToString:@"traineeAddress"]){
        if (!settingsValues.address)
            settingsValues.address = [[NSMutableArray alloc]initWithObjects:[change valueForKey:@"new"], nil];

        else
            [settingsValues.address replaceObjectAtIndex:0 withObject:[change valueForKey:@"new"]];
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!