標籤:
一. KVC : key value coding,通常用來給某一個對象的屬性賦值
1. KVC賦值
// 1.1 建立人LDPerson *p = [[LDPerson alloc] init];self.person = p;// 1.2 建立狗LDDog *dog = [[LDDog alloc] init];// 1.3 將狗賦值給人[p setValue:dog forKeyPath:@"dog"];// 1.4 通過kvc給dog的weight屬性賦值 \賦值時會自動找到人擁有的dog的weight屬性[p setValue:@20.0 forKeyPath:@"dog.weight"];NSLog(@"books = %@", [p valueForKeyPath:@"dog.weight"]);[dog print];
2. KVC字典賦值
// 2.1 建立一個字典,person的屬性為鍵,對應賦值NSDictionary *dict = @{@"name": @"jack", @"age": @"10", @"height": @"1.65"};// 2.2 通過字典中的鍵找到person對象屬性進行賦值[p setValuesForKeysWithDictionary:dict];NSLog(@"name = %@, age = %@, height = %@", [p valueForKeyPath:@"name"], [p valueForKeyPath:@"age"], [p valueForKeyPath:@"height"]);
3. 自訂字典
// 3.1 定義字典NSDictionary *dict1 = @{@"name": @"jim", @"age": @"20", @"height": @"1.75", @"books": @[@{@"price": @"100"}, @{@"price": @"98"}, @{@"price": @"200"}, @{@"price": @"198"}], @"dog": @{@"weight": @"45.89"}};// 3.2 kvc賦值[p setValuesForKeysWithDictionary:dict1];// 3.3 輸出boos中存放的是字典NSLog(@"books = %@", [p valueForKeyPath:@"books"]);NSLog(@"dog.weight = %@", [p valueForKeyPath:@"dog.weight"]);// 3.4 遍曆,讓books中存放字典NSMutableArray *arrayM = [NSMutableArray array];for (NSDictionary *dict in [p valueForKeyPath:@"books"]) { LDBook *book = [LDBook bookWithDict:dict]; [arrayM addObject:book];}[p setValue:arrayM forKeyPath:@"books"];NSLog(@"books = %@", [p valueForKeyPath:@"books"]);
4. KVC取值
NSMutableArray *tempM = [NSMutableArray array];// 4.1 kvc取出出數組books中price的值for (LDBook *book in [p valueForKeyPath:@"books"]) { [tempM addObject:[book valueForKeyPath:@"price"]];}NSLog(@"%@", tempM);// 4.2 kvc取出數組中price的最大值/最小值/平均值/個數NSLog(@"Max = %@", [[p valueForKeyPath:@"books"] valueForKeyPath:@"@max.price"]);NSLog(@"Min = %@", [[p valueForKeyPath:@"books"] valueForKeyPath:@"@min.price"]);NSLog(@"Avg = %@", [[p valueForKeyPath:@"books"] valueForKeyPath:@"@avg.price"]);NSLog(@"count = %@", [[p valueForKeyPath:@"books"] valueForKeyPath:@"@count.price"]);
二. KVO : Key Value OBserver (觀察者)
通過KVO可以觀察某一個對象的屬性值發生改變
1. 給Person建立一個觀察者,觀察Person的name屬性
[p addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
2. 修改Person的name的值
[p setValue:@"ldd" forKey:@"name"];
3. 當Person的name的值發生改變時,會回調
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
#pragma mark - 實現KVO回調方法/** * 當對象的屬性發生改變會調用該方法 * * @param keyPath 監聽的屬性 * @param object 監聽的對象 * @param change 新值和舊值 * @param context 額外的資料 */- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{ NSLog(@"KeyPath = %@", keyPath); NSLog(@"object = %@", object); NSLog(@"change = %@", change);}
4. 當回調完成之後銷毀觀察者
/** * 銷毀Person的觀察者 */- (void)dealloc{ [self.person removeObserver:self forKeyPath:@"name" context:nil];}
iOS開發UI之KVC(取值/賦值) - KVO (觀察某個對象的某個屬性的改變)