KVC
Key-Value-Coding
setValue:forKey:
setValue:forKeyPath:
valueForKey:
valueForKeyPath:
是个比较有用的东西,大家都这么说,嗯,那我慢慢体会。
听说用它可以设置和访问私有的成员变量,嗯,就是说只要你定义了一个变量就逃不过他的火眼金睛。除非你在.m里面定义的全局变量。
它可以修改一些系统设为readonly的属性。
还有就是他在访问一个类的数组属性时非常方便。
比如我想访问一个属性中的属性值,就利用keyPath就可以了。
例如:
// Parent.h
@property(nonatomic, strong) NSArray *childrens;
// Children.h
@property(nonatomic, strong) NSString *name;
// main.m
Children *child1 = [[Children alloc] init];
child1.name = @"haha";
Children *child2 = [[Children alloc] init];
child2.name = @"xixi";
Children *child3 = [[Children alloc] init];
child3.name = @"xixi";
Children *child4 = [[Children alloc] init];
child4.name = @"xixi";
Parent *parent = [[Parent alloc] init];
parent.childrens = @[child1, child2, child3, child4];
NSLog(@"孩子的名字-> %@", [parent valueForKeyPath:@"childrens.name"]);
打印结果:
孩子的名字-> (
haha,
xixi,
xixi,
xixi
)
嗯,自己体会吧。