开发者

setValue:forKey: operation?

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(counte开发者_如何学Pythonr=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: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.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜