我现在正在学习键值观察,有一个非常简单的 KVO 项目有一个小问题,即在observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
方法调用时不打印属性新值的变化。这很奇怪,希望有人帮我找出问题所在,我非常感谢!
这是我的源代码:
视图控制器.h
#import <UIKit/UIKit.h>
@class Person;
@interface ViewController : UIViewController
@property (nonatomic, strong) Person *person;
@end
视图控制器.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
人.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property (nonatomic, strong) NSString *fullName;
@end
人.m
#import "Person.h"
@implementation Person
@synthesize fullName = _fullName;
@end