kvc(键-值编码)

时间:2022-05-25 03:57:35

kvc(键-值编码)

{ NSString *_name;

Author *_author;

NSArray *_kvcArray;

float price;}

//kvc,setValue 的设的值是 “要设置的值” forKey 设置的是对象的属性,如果不是的话要将其转化对象(int folat,char,double)

Book *book = [[Book alloc] init];

//        Author *author = [[Author alloc] init];

//        [author setValue:@"jack" forKey:@"aname"];

//

//        //间接访问

//        [book  setValue:@"ipa set Value" forKey:@"name"];

//        [book setValue:author forKey:@"author"];

//

//        //路径访问

//        [book setValue:@"tom" forKeyPath:@"author.aname"];

//        NSString *authorName = [book valueForKeyPath:@"author.aname"];

//

//一对多访问

NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:3];

for (int i = 0; i < 3; i++) {

Book *book = [[Book alloc] init];

NSString *string = [NSString stringWithFormat:@"job_%d",i];

[book setValue:@(12+i) forKey:@"price"];

[book setValue:string forKey:@"name"];

[mutableArray addObject:book];

[book release];

}

//     [book setValue:mutableArray forKey:@"_kvcArray”];

//

//        NSArray *bookArray = [book valueForKeyPath:@"_kvcArray.name”];//通过数组的中的属性名路径访问,体现了键值访问

//上面这种访问相当于这种

//      NSArray *bookArray = [mutableArray valueForKeyPath:@“_name”];//这也是对mutableArray 的属性进行路劲访问

//

//        NSLog(@"bookArray:%@",bookArray);

//

//        NSLog(@"%@",authorName);

//运算 avg sum count min max,运算的必须是NSNumber 和 数据类型,返回值是NSNumber,   setValue 时,引用计数会加1

[book setValue:mutableArray forKey:@"_kvcArray”];//将book 的 _kvcArray属性设值

NSNumber *sum = [book valueForKeyPath:@"_kvcArray.@sum.price”];//格式是(属性.@运算方式.属性对象中的属性)//使用运算符的前提是 NSNumber 的数据类型

NSLog(@"sum : %@",sum);