KVC( Key value coding )
Animal.m
@interface Animal ()
{
NSString *_dna;
}
@property (nonatomic,copy) NSString *DNA;
@property (nonatomic,strong) Dog *dog;
@end
//當(dāng)設(shè)置的實(shí)例變量為標(biāo)量朋腋,且賦值為空,
//標(biāo)量: int, float, double; NSString是OC對(duì)象
- (void)setNilValueForKey:(NSString *)key{
NSLog(@"-----Nil------");
}
//當(dāng)取得值沒(méi)有定義時(shí)
- (id)valueForUndefinedKey:(NSString *)key {
return key;
}
- (void)setValue:(id)value forUndefinedKey:(NSString *)key{
NSLog(@"--------key: %@", key);
}
Dog.m
@interface Dog ()
{
NSString *_dogName;
}
@end
ViewController
- (void)viewDidLoad {
[super viewDidLoad];
Animal *animal = [Animal new];
[animal setValue:@"---animal--dna---" forKey:@"_dna"];
NSString *dna = (NSString*)[animal valueForKey:@"_dna"];
NSLog(@"dna = %@",dna);
//用property生成的變量會(huì)自動(dòng)生成帶下滑線的伸但,所以?xún)蓚€(gè)都一樣
[animal setValue:@"lol" forKey:@"_DNA"];
NSString *DNA = (NSString*)[animal valueForKey:@"_DNA"];
NSLog(@"DNA = %@",DNA);
//keyPath用于隔級(jí)賦值
Dog *dog = [Dog new];
// [dog setValue:@"laohei" forKey:@"name"];
[animal setValue:dog forKey:@"dog"];
[animal setValue:@"--dogName--" forKeyPath:@"dog.dogName"];
NSString *dogName = [animal valueForKeyPath:@"dog.dogName"];
NSLog(@"dogName = %@",dogName);
}
KVO ( Key Value Oberser )
Animal.h
@interface Animal : NSObject
@property (nonatomic, assign)double height;
@end
ViewController
@interface ViewController ()
{
Animal *_animal;
}
@end
@implementation ViewController
- (void)viewDidLoad {
_animal = [Animal new];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
_animal.height = 11;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
_animal.height = 22;
});
});
[_animal addObserver:self forKeyPath:@"height" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
}
//觀察對(duì)象應(yīng)該設(shè)為全局的腻异,不然沒(méi)法執(zhí)行此函數(shù)觀察者就會(huì)被銷(xiāo)毀
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
NSLog(@"keyPath:%@",keyPath);
NSLog(@"change:%@",change);
NSLog(@"--value:%@",change[@"new"]);
}
//在觀察對(duì)象銷(xiāo)毀的時(shí)候惑艇,觀察者一定要銷(xiāo)毀
- (void)dealloc{
[_animal removeObserver:self forKeyPath:@"height"];
}
@end
當(dāng)Animal中此函數(shù)的返回值為NO時(shí)
+(BOOL)automaticallyNotifiesObserversOfHeight{
return NO;
}
如果想讓觀察者知道改變的時(shí)機(jī),則應(yīng)該寫(xiě)代碼如:
[ _animal willChangeValueForKey:@"height"];
_animal.height = 11;
[ _animal didChangeValueForKey:@"height"];