https://stackoverflow.com/questions/38588160/kvo-observe-property-of-an-object-contained-in-a-nsarray
可以使用addObserver:toObjectsAtIndexes:
方法。
举例:
@interface Car : NSObject
@property(nonatomic,assign)NSInteger carValue;
@end
...
@interface ViewController ()
@property(nonatomic, strong) NSArray<Car *> *cars;
@end
- (void)viewDidLoad {
[super viewDidLoad];
Car *car1 = [[Car alloc]init];
Car *car2 = [[Car alloc]init];
self.cars = @[car1 ,car2];
[self.cars addObserver:self toObjectsAtIndexes:[NSMutableIndexSet indexSetWithIndexesInRange:NSMakeRange(0, self.cars.count)] forKeyPath:@"carValue" options:0 context:nil];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
Car *c1 = self.cars[0];
c1.carValue = c1.carValue + 100;
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSLog(@"--%@-",keyPath);
}
最后不要忘了移除观察者。
一篇介绍kvo不错的文章:深入理解KVO