开发者

When to use self and when to use retain

开发者 https://www.devze.com 2023-01-16 17:17 出处:网络
am working my way through the \"Beginning iPad Development\" Apress book and hav开发者_C百科e noticed that sometimes when the author is assigning values to a property they will use:

am working my way through the "Beginning iPad Development" Apress book and hav开发者_C百科e noticed that sometimes when the author is assigning values to a property they will use:

self.variable = value;

and other times, they will use:

variable = [value retain];

In both cases variable is a property defined as:

@property (nonatomic, retain) TYPE variable;

I wondered if anyone knew why this is done to help me better understand

Thanks, William


One place where you use the second form is if you're defining your own setter method. You can't assign to self.variable there, because you'll call the setter recursively. So for example this is wrong:

-(void)setVariable:(TYPE*)value {
    if (value != variable) {
        [variable release];
        self.variable = [value retain]; // WRONG! Calls 
                                        // [self setVariable:[value retain]]
    }
}

This is right:

-(void)setVariable:(TYPE*)value {
    if (value != variable) {
        [variable release];
        variable = [value retain];
    }
}

Does that help?


They are often equivalent memory-wise. The compiler turns self.variable = value into [self setVariable:value] which then calls the generated setter (if you're using @synthesize) and retains it for you.

0

精彩评论

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