仍然无法使用 NSArray 对象来消化 KVO。我的要求是例如假设车库里有多辆汽车。我想观察汽车轮胎性能的变化,比如前轮胎升级还是后轮胎。
汽车.h
@property(nonatomic, strong) NSString *frontTyre;
@property(nonatomic, strong) NSString *backTyre;
车库.h
@property(nonatomic, strong) NSArray *cars; //Think there are two cars in the garage.
在 CarOwner.m 中
[Garage addObserver:self forKeyPath"cars" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];]
-(void)observeValueForKeyPathNSString *)keyPath ofObjectid)object changeNSDictionary *)change contextvoid *)context
{
if([keyPath isEqualToString"cars"])
{
//Here I am able to get the car object which got a type upgrade.
//But how to know which tyre got upgraded?
}
}
在升级汽车轮胎时:
[self willChange:NSKeyValueChangeSetting valuesAtIndexes:index forKey"remoteUsers"];
[car1.frontTyre = @"upgraded"];
[self didChange:NSKeyValueChangeSetting valuesAtIndexes:index forKey"remoteUsers"];
我应该去this或 this方法?或者您可能有任何其他建议。
Best Answer-推荐答案 strong>
您可以按如下方式使用添加观察者:
[Garage.cars addObserver:self toObjectsAtIndexes:[NSMutableIndexSet indexSetWithIndexesInRange:NSMakeRange(0, Garage.cars.count)] forKeyPath"frontTyre" options:0 context:nil];
记得在必要时移除观察者。
关于ios - KVO - 观察 NSArray 中包含的对象的属性,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/38588160/
|