监听一个数组的变化

        首先个人认为既然是监听数组的变化,那必然是NSMutableArray,只有它才能添加、删除数组元素。抛砖引玉,希望有其他或更好的方法的读者不要吝啬,拿出来分享下。

核心代码:

[[self mutableArrayValueForKey:@"array"]addObject:object]、

[[self mutableArrayValueForKey:@"array"]removeObject:object] 等,关键部位还是[self mutableArrayValueForKey:@"array"];

这样就可以触发KVO方法了

例子:

@interface Controller : UIViewController

@property (nonatomic, strong) NSMutableArray *array;

@end   

- (void)viewDidLoad {

        [super viewDidLoad];

        _array = [NSMutableArray arrayWithCapacity:2];

        [self addObserver:self forKeyPath:@"array" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];

}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {    

if ([keyPath isEqualToString:@"array"]) {        NSLog(@"%zd”,self.array.count);    }

}

/// 改变演示

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {                        

        [[self mutableArrayValueForKey:@"array"] addObject:@“fsfs”];

}

- (void)dealloc {    

[self removeObserver:self forKeyPath:@"array"];

}

你可能感兴趣的:(监听一个数组的变化)