-
KVC
KVC是KeyValueCoding的簡(jiǎn)稱,它是一種可以直接通過字符串的名字(key)來訪問類屬性的機(jī)制。而不是通過調(diào)用Setter、Getter方法訪問周伦。
Person.h
@interface Person : NSObject
@property (strong, nonatomic) NSString *name;
@property (assign, nonatomic) NSInteger age;
@property (strong, nonatomic) NSString *code;
@property (assign, nonatomic) double height;
@end
main.m
NSDictionary *dic = @{@"name" : @"admin",
@"age" : @13, @"code" : @"111222333",
@"height" : @12.4};
Person *person = [[Person alloc] init];
person.name = @"person name";
//KVC
[person setValue:@"KVC name" forKey:@"name"];
[person setValue:@12 forKey:@"age"];
[person setValue:@"112233" forKey:@"code"];
[person setValue:@15.9 forKey:@"height"];
// 利用KVC將json轉(zhuǎn)Model
for (NSString *key in dic) {
[person setValue:dic[key] forKey:key];
}
// 一次性轉(zhuǎn)
[person setValuesForKeysWithDictionary:dic];
-
KVO
KVO,即:Key-Value Observing,它提供一種機(jī)制未荒,當(dāng)指定的對(duì)象的屬性被修改后专挪,則對(duì)象就會(huì)接受到通知。簡(jiǎn)單的說就是每次指定的被觀察的對(duì)象的屬性被修改后片排,KVO就會(huì)自動(dòng)通知相應(yīng)的觀察者了寨腔。
設(shè)置監(jiān)聽者
- (void)setStock:(Stock *)stock {
_stock = stock;
// 1. 設(shè)置監(jiān)聽(注冊(cè)監(jiān)聽)
// 參數(shù):監(jiān)聽者,監(jiān)聽值率寡,監(jiān)聽選項(xiàng)迫卢,上下文
[_stock addObserver:self forKeyPath:@"price" options:NSKeyValueObservingOptionNew context:nil];
}
處理監(jiān)聽
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
NSLog(@"keypath : %@", keyPath);
NSLog(@"object : %@", object);
NSLog(@"change : %@", change);
// 2. 處理監(jiān)聽(當(dāng)股票漲到40以上后,調(diào)用sell方法賣出)
NSNumber *newPriceNumber = change[@"new"];
if ([newPriceNumber intValue] >= 40) {
[self sell];
}
}
change字典與添加觀察者中的參數(shù)相對(duì)應(yīng)
NSKeyValueObservingOptions change
-------------------------------------------
NSKeyValueObservingOptionNew @{kind = ;new = ;}
NSKeyValueObservingOptionOld @{kind = ;old = ;}
NSKeyValueObservingOptionInitial @{kind = ;}
NSKeyValueObservingOptionPrior @{kind = 1;
notificationIsPrior = 1;} @{kind = 1;} @{kind = 1;notificationIsPrior = 1;}
移除監(jiān)聽
- (void)dealloc {
// 3. 移除監(jiān)聽
[_stock removeObserver:self forKeyPath:@"price"];
}