1.KVO(key-value observering)是指當(dāng)對(duì)象的屬性值改變的時(shí)候镐捧,允許另外一個(gè)對(duì)象接受通知,其中context可以用來(lái)區(qū)分該通知是發(fā)給基類還是自己的蜘犁。
#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.如果屬性不是通過(guò)存取方法來(lái)改變值的砰诵,例如直接給實(shí)例變量賦值,_name=xxx亚皂,這個(gè)時(shí)候可以顯示觸發(fā)通知。
-(void) updateLastValue
{
[self willChangeValueForKey:@"height"];
_height++;
[self didChangeValueForKey:@"height"];
}
3.有時(shí)候一個(gè)屬性的改變會(huì)引起另外一個(gè)屬性改變国瓮,我們可以通過(guò)keyPathsForValuesAffecting使某個(gè)屬性觸發(fā)通知時(shí)灭必,也觸發(fā)另外一個(gè)屬性的改變通知狞谱,keyPathsForValuesAffecting后面為要影響的屬性名,首字母大寫(xiě)禁漓,不需要聲明跟衅。
-(void) updateLastValue
{
[self willChangeValueForKey:@"height"];
_height++;
_size=_height*2;
[self didChangeValueForKey:@"height"];
}
+(NSSet*) keyPathsForValuesAffectingSize
{
return [NSSet setWithObject:@"height"];
}