tags:

views:

236

answers:

2

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

+3  A: 

The answer is yes, the two code snippets essentially do the same thing. setValue:forKey doesn'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:forKey would still be able to set them to point to animalArray but it wouldn't be retained.

Felixyz
Thank you Felixyz, thats what I was missing that setValue:forKey called the synthesized method, much appreciated. Also the "iVarName" I was thinking about that, your right propertyName does fit a lot better.
fuzzygoat
+2  A: 

First of all [self setMyArray_1: animalArray]; does not just set pointers, but also retains input array - as it calls automatically generated setter method and its behaviour is defined in corresponding property attributes:

@property(nonatomic, retain) NSArray *myArray_1; // retain !

How accessor method is searched described in Accessor Search Implementation Details in "KVC Coding Guide":

When the default implementation of setValue:forKey: is invoked for a property the following search pattern is used:

  1. The receiver’s class is searched for an accessor method whose name matches the pattern -set<Key>:.

So as your class has necessary accesor method (declared via property) this method (setMyArray_i) will get called (and retain your array).

Vladimir