1.KVO(key-value observering)是指当对象的属性值改变的时候,允许另外一个对象接受通知,其中context可以用来区分该通知是发给基类还是自己的。
#import "TestObserver.h"
@implementation TestObserver
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSNumber *oldValue=[change objectForKey:NSKeyValueChangeOldKey];
NSNumber *newValue=[change objectForKey:NSKeyValueChangeNewKey];
NSLog(@"Observed:%@ of %@ was changed from %@ to %@",keyPath,object,oldValue,newValue);
}
@end
#import <Foundation/Foundation.h>
#import "TestClass.h"
#import "TestObserver.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
TestClass *testObj=[[TestClass alloc]init];
__unused TestObserver *testObserver=[[TestObserver alloc]init];
//添加观察者
[testObj addObserver:testObserver
forKeyPath:@"height"
options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld
context:nil];
//两秒更新一次值
__unused NSTimer *timer=[NSTimer scheduledTimerWithTimeInterval:2.0 target:testObj
selector:@selector(updateLastValue) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] run];
}
return 0;
}
2.如果属性不是通过存取方法来改变值的,例如直接给实例变量赋值,_name=xxx,这个时候可以显示触发通知。
-(void) updateLastValue
{
[self willChangeValueForKey:@"height"];
_height++;
[self didChangeValueForKey:@"height"];
}
3.有时候一个属性的改变会引起另外一个属性改变,我们可以通过keyPathsForValuesAffecting使某个属性触发通知时,也触发另外一个属性的改变通知,keyPathsForValuesAffecting后面为要影响的属性名,首字母大写,不需要声明。
-(void) updateLastValue
{
[self willChangeValueForKey:@"height"];
_height++;
_size=_height*2;
[self didChangeValueForKey:@"height"];
}
+(NSSet*) keyPathsForValuesAffectingSize
{
return [NSSet setWithObject:@"height"];
}