我很好奇setValue:forKey:在下面的代码片段中发生了什么:它只是将指针设置为指向每个数组,类似于...
[self setMyArray_1: animalArray];
[self setMyArray_2: animalArray];
[self setMyArray_3: animalArray];还有: setValue:forKey是否保留数组?我猜是这样的(如上所述)
代码片段:
// INTERFACE
@property(nonatomic, retain) NSArray *myArray_1;
@property(nonatomic, retain) NSArray *myArray_2;
@property(nonatomic, retain) NSArray *myArray_3;
// IMPLEMENTATION
@synthesize myArray_1;
@synthesize myArray_2;
@synthesize myArray_3;
for(counter=1; counter<=3; counter++) {
NSArray *animalArray = [[NSArray alloc] initWithObjects:@"cat", @"rat", nil];
NSString *propertyName = [[NSString alloc] initWithFormat:@"myArray_%d", counter];
[self setValue:animalArray forKey:propertyName];
[animalArray release];
[propertyName release];
}加里
发布于 2010-02-19 20:11:17
答案是肯定的,这两个代码片段基本上做了相同的事情。setValue:forKey不会保留数组,但它会找到合成的setMyArray_x方法,该方法会保留该数组。最好将iVarName称为propertyName或keyName。然而,如果你没有声明和合成属性,而是只有四个animalArray,setValue:forKey仍然可以将它们设置为指向ivar,但它不会被保留。
发布于 2010-02-19 20:14:12
首先,[self setMyArray_1: animalArray]; 不只是设置指针,还保留了输入数组-因为它调用自动生成的方法,其行为在相应的属性属性中定义:
@property(nonatomic, retain) NSArray *myArray_1; // retain !在《KVC编码指南》的Accessor Search Implementation Details中描述了如何搜索存取器方法:
当为属性调用setValue:forKey:的默认实现时,将使用以下搜索模式:
在接收器的类中搜索其名称与模式-set<Key>:.匹配的访问器方法
因此,当你的类有必要的accesor方法(通过属性声明)时,这个方法(setMyArray_i)将被调用(并保留你的数组)。
https://stackoverflow.com/questions/2296072
复制相似问题