ios开发--KVO浅析

NineYao 2013-01-15

目标:监听NSMutableArray对象中增加了什么

代码如下:

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.dataArray = [NSMutableArray arrayWithObject:@"1"];
    [self addObserver:self forKeyPath:@"dataArray" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:NULL];
     
}
- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSLog(@"%@", keyPath);
    NSLog(@"%@", object);
    NSLog(@"%@", change);
}
- (IBAction)add:(id)sender
{
    NSArray *addData = [NSArray arrayWithObjects:@"11", @"12", @"13", nil];
    [self.dataArray addObjectsFromArray:addData];
    
    self.dataArray = [NSMutableArray arrayWithObject:@"2"];
}

输入日志:

2013-01-15 16:05:10.120 KVOTest[2199:907] dataArray
2013-01-15 16:05:10.121 KVOTest[2199:907] <ZZTViewController: 0x20846590>
2013-01-15 16:05:10.123 KVOTest[2199:907] {
    kind = 1;
    new =     (
        2
    );
    old =     (
        1,
        11,
        12,
        13
    );
}

经过测试得如下结论:kvo监听的是对象指针的变动,NSString、int、float等对象的变动(abc = @"123"、abc = 12、abc = 12.2)皆为指针的变动,所以通过此方式来捕捉array的变化是不可行的

但,我们可以通过此方式来做控件属性的变动。如下:

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.personObject = [PersonObject personObjectWithBankInstance:[BankObject bankObjectWithAccountBalance:10]];
    
    [self.personObject addObserver:self forKeyPath:@"bankInstance.accountBalance" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:NULL];    // 此处注意是监听personObject对象下的bankInstance的accountBalance变化
}
- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSLog(@"%@", keyPath);
    NSLog(@"%@", object);
    NSLog(@"%@", change);
}
- (IBAction)add:(id)sender
{
    [self.personObject.bankInstance setAccountBalance:2111];
}

 输出日志:

2013-01-15 16:05:10.111 KVOTest[2199:907] bankInstance.accountBalance
2013-01-15 16:05:10.116 KVOTest[2199:907] <PersonObject: 0x20856180>
2013-01-15 16:05:10.118 KVOTest[2199:907] {
    kind = 1;
    new = 2111;
    old = 10;
}

如有问题,请留言共同探讨。

相关推荐

定格 / 0评论 2019-12-11