KVC的使用
2019-07-26 本文已影响40人
小白的天空
小白的简书集合
上篇已经介绍了KVC的调用机制,我们这篇将具体介绍下KVC的使用吧。
我们可以将一个字典返回一个自定义的model,并且我们可以重定义字典的key
@interface LWFKVCPersonModel : NSObject
@property (nonatomic, assign) NSInteger userId;
@property (nonatomic, assign) NSInteger age;
@property (nonatomic, copy) NSString *name;
@end
@implementation LWFKVCPersonModel
- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
//字典中包含有“id”的特殊字符,这时候我们可以重定向指定为我们自己的属性
if ([key isEqualToString:@"id"]) {
self.userId = [value integerValue];
}
}
- (NSString *)description {
return [NSString stringWithFormat:@"userId:%ld, age:%ld, name:%@", self.userId, self.age, self.name];
}
@end
- (void)test2 {
NSDictionary *dictionary = @{@"id" : @"123", @"name" : @"lwf", @"age" : @"12"};
LWFKVCPersonModel *model = [[LWFKVCPersonModel alloc] init];
[model setValuesForKeysWithDictionary:dictionary];
NSLog(@"%@", model);
}
我们可以看到正确的打印出来我们所需要的属性
![](https://img.haomeiwen.com/i13007216/4f2c430eb3d625e9.jpg)
当我们对一个数组集合操作时:系统只会返回一个包含该属性的集合
NSMutableArray *mutArr = [NSMutableArray array];
for (NSInteger i = 0; i < 5; i++) {
LWFKVCPersonModel *model = [LWFKVCPersonModel new];
model.age = i;
model.name = [NSString stringWithFormat:@"lwf_%ld", i];
model.userId = i;
[mutArr addObject:model];
}
NSLog(@"%@", [mutArr mutableArrayValueForKey:@"name"]);
![](https://img.haomeiwen.com/i13007216/53fa725e89c95bdf.jpg)
当我们操作一个数组中没有该属性的时候,系统会自动停止改程序,并将保存之前的状态返回给我们
[mutArr addObject:@"name"];
id obj = [mutArr mutableArrayValueForKey:@"name"];
NSLog(@"%@,%p,%@", obj, obj, [obj class]);
![](https://img.haomeiwen.com/i13007216/d8148946ff22b2ca.jpg)
![](https://img.haomeiwen.com/i13007216/a7dc83d4902846e0.jpg)
从图片中我们可以看出NSKeyValueSlowMutableArray是系统实现的一个私有的类,我们并不能去干预它,所以使用集合的时候要确保含有该属性,要不然我们只能空欢喜一场
我们也看看KVC支持的运算符吧
NSLog(@"sum:%@", [mutArr valueForKeyPath:@"@sum.age"]);
NSLog(@"avg:%@", [mutArr valueForKeyPath:@"@avg.age"]);
NSLog(@"min:%@", [mutArr valueForKeyPath:@"@min.age"]);
NSLog(@"max:%@", [mutArr valueForKeyPath:@"@max.age"]);
NSLog(@"count:%@", [mutArr valueForKeyPath:@"@count.age"]);
![](https://img.haomeiwen.com/i13007216/e5ae3e251d011028.jpg)
最重要的是别忘了上篇我们所讲的KVC get时候的顺序哟:我们可以直接获取一个方法,就像这样:
@interface LWFKVCPetModel : NSObject
@end
@implementation LWFKVCPetModel
- (NSString *)description {
return NSStringFromClass([self class]);
}
@end
LWFKVCPetModel *petModel = [LWFKVCPetModel new];
[mutArr addObject:petModel];
NSLog(@"%@", [mutArr valueForKeyPath:@"description"]);
![](https://img.haomeiwen.com/i13007216/88cbc1183cb84cdb.jpg)