KVOとKVC
2013 ワード
1 KVO
2.KVC
- (void)viewDidLoad {
[super viewDidLoad];
self.p = [[Person alloc] init];
self.p.age = 20;
//KVO
//
[self.p addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
/*
* keyPath ( )
* object
* change
* context void * == id
*/
}
// ,
-(void)dealloc
{
[self.p removeObserver:self forKeyPath:@"age"];
}
2.KVC
- (void)viewDidLoad {
[super viewDidLoad];
self.p = [[Person alloc] init];
self.p.age = 20;
//KVC
//1. key
int age = [[self.p valueForKey:@"age"] intValue];
/*
* :valueForKey id,id , NSNumber
*/
//2.
//3.keyPath key:keyPath key ,key , keyPath
[self.p valueForKeyPath:@"dog.name"];
//4.keyPath
WTBook *b1 = [[WTBook alloc] init];
b1.name = @"kuaihua";
b1.price = 100.6;
WTBook *b2 = [[WTBook alloc] init];
b2.name = @"prixe";
b2.price = 5.6;
WTBook *b3 = [[WTBook alloc] init];
b3.name = @"jiuxin";
b3.price = 50.5;
self.p.books = @[b1,b2,b3];
// p.books name
NSArray *names = [self.p.books valueForKeyPath:@"name"];
NSArray *names2 = [self.p valueForKeyPath:@"books.name"];
//
[self.p valueForKeyPath:@"books.@count"];
// p book
[self.p valueForKeyPath:@"[email protected]"];
[self.p valueForKeyPath:@"[email protected]"];
[self.p valueForKeyPath:@"[email protected]"];
[self.p valueForKeyPath:@"[email protected]"];
}