I am curious what is happening with setValue:forKey: in the code snippet below: is it just setting the pointer to point to each array, similar to …
[self setMyArray_1: animalArray];
[self setMyArray_2: animalArray];
[self setMyArray_3: animalArray];
Also: does setValue:forKey retain the array? I am guessing it does (as the above would)
Code Snippet:
// 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];
}
gary
The answer is yes, the two code snippets essentially do the same thing.
setValue:forKeydoesn’t retain the array, but it finds the synthesized setMyArray_x method which in turn retains the array. iVarName should better be called propertyName or keyName. However, if you hadn’t declared and synthesized the properties, but instead just had four ivars,setValue:forKeywould still be able to set them to point toanimalArraybut it wouldn’t be retained.