KVC在iOS开发中是绝不可少的利器,这种基于运行时的编程方式极大地提高了灵活性,简化了代码,KVC算是iOS开发的一种黑魔法。
使用场景举例:
如果想要将以下的所有merchantType字段存成一个不可变的数组,以备用
{
"code": "000000",
"data": {
"businessInfos": [{
"distance": "561.32",
"businessId": "BD2017102109081500069783",
"businessName": "丽马体验店",
"businessAreaName": "市辖区",
"merchantType": "CF99",
}, {
"distance": "1553.78",
"businessId": "BD2017070611050100012749",
"businessName": "麦克咖啡",
"businessAreaName": "秀洲区",
"merchantType": "BK",
}, {
"distance": "1593.86",
"businessId": "BD2017070611022200012748",
"businessName": "大麦客直销中心",
"businessAreaName": "秀洲区",
"merchantType": "WD",
"businessImage": "http://fdfs.xylbn.cn/group1/M00/05/38/wKgthloFRsaAB9oKAAAZ_LoHwQM515.png"
}, {
"distance": "1596.76",
"businessId": "BD2017082315125500057012",
"businessName": "阿拉丁麻辣烫",
"businessAreaName": "市辖区",
"merchantType": "CF1",
"businessImage": "http://fdfs.xylbn.cn/group1/M00/02/44/wKgthVlUrIeAZ60_AAC-VaUFHrc830.png"
}, {
"distance": "1596.99",
"businessId": "BD2017082315264300057032",
"businessName": "玛丽莲甜品(嘉兴万达店)",
"businessAreaName": "市辖区",
"merchantType": "CF3",
}, {
"distance": "1597.01",
"businessId": "BD2017082314390700056966",
"businessName": "小淮娘",
"businessAreaName": "桐乡市",
"merchantType": "CF4",
}]
},
"msg": "执行成功"
}
常规的方法:
self.shopArray=[[[self dictionaryWithContentsOfJSONString:@"shop.json"] objectForKey:@"data"] objectForKey:@"businessInfos"];
NSMutableArray * merchantTypeArrMutableArr = [NSMutableArray array];
for(NSDictionary *dict in self.shopArray){
NSString * str = dict[@"merchantType"];
[merchantTypeArrMutableArr addObject:str];
}
NSArray * merchantTypeArr = [NSArray arrayWithArray: merchantTypeArrMutableArr];
NSLog(@"%@ merchantTypeArr", merchantTypeArr);
巧妙的方法:
self.shopArray=[[[self dictionaryWithContentsOfJSONString:@"shop.json"] objectForKey:@"data"] objectForKey:@"businessInfos"];
NSArray * merchantTypeArr = [self.shopArray valueForKey:@"merchantType"];
NSLog(@"%@ merchantTypeArr", merchantTypeArr);
如果还想获取每个merchantType字段的一些属性,比如字符长度,然后生成数组,同样可以一行代码搞定:
NSArray* merchantTypeLengthArr = [merchantTypeArr valueForKeyPath:@"length"];
NSLog(@"%@ merchantTypeLengthArr", merchantTypeLengthArr);
再复杂点的场景也能极简处理,比如再求出所有merchantType字段字符的总长度
NSNumber* merchantTypeAllLength= [merchantTypeLengthArr valueForKeyPath:@"@sum.self"];
NSLog(@"%@ merchantTypeAllLength", merchantTypeAllLength);