I'm now learning key value observing, have a very simple KVO project have a little problems that dont't print property new value changes when observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
method called. That's very weird, hope someone help me find where problems occurred, i'm very appreciated that!
Here is my source code:
ViewController.h
#import <UIKit/UIKit.h>
@class Person;
@interface ViewController : UIViewController
@property (nonatomic, strong) Person *person;
@end
ViewController.m
#import "ViewController.h"
#import "Person.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize person;
- (void)viewDidLoad
{
[super viewDidLoad];
self.person = [[Person alloc] init];
[self changeName];
[self.person addObserver:self
forKeyPath:@"fullName"
options:NSKeyValueObservingOptionNew
context:NULL];
}
- (void)changeName
{
self.person.fullName = @"Andy";
}
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
if ([keyPath isEqualToString:@"fullName"])
{
NSLog(@"%@", change);
NSString *string = [change objectForKey:NSKeyValueChangeNewKey];
NSLog(@"%@", string);
}
}
- (void)dealloc
{
[self.person removeObserver:self forKeyPath:@"fullName"];
}
@end
Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property (nonatomic, strong) NSString *fullName;
@end
Person.m
#import "Person.h"
@implementation Person
@synthesize fullName = _fullName;
@end
You're changing the name before you're adding the observer. Swap this:
[self changeName];
[self.person addObserver:self
forKeyPath:@"fullName"
options:NSKeyValueObservingOptionNew
context:NULL];
...for this:
[self.person addObserver:self
forKeyPath:@"fullName"
options:NSKeyValueObservingOptionNew
context:NULL];
[self changeName];