#import <Foundation/Foundation.h>
@interface MObject : NSObject
{
int _value;
}
@end
@implementation MObject
- (id)init
{
self = [super init];
if (self) {
_value = 0;
}
return self;
}
@end
@interface MObserver : NSObject
@end
@implementation MObserver
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
if ([object isKindOfClass:[MObject class]] &&
[keyPath isEqualToString:@"value"]) {
// 获取value的新值
NSNumber *valueNum = [change valueForKey:NSKeyValueChangeNewKey];
NSLog(@"value is %@", valueNum);
}
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
MObject *obj = [[MObject alloc] init];
MObserver *observer = [[MObserver alloc] init];
//调用kvo方法监听obj的value属性的变化
[obj addObserver:observer forKeyPath:@"value" options:NSKeyValueObservingOptionNew context:NULL];
[obj setValue:@2 forKey:@"value"];
}
return 0;
}
这样调用KVC为什么能触发KVO?