开发者

Memory Management assigning a new object

Suppose I have instance variable where I defined as retained in the header file. I assign an object to it when the class is initialized. Now suppose in some function I assign a new object to my instance variable. Do I need to release th开发者_运维技巧e previous retained object?


Depends on how you assign it. If you assign it directly to the member variable, then yes, you would need to release the old one. If you assign it using the public property, e.g. self.propertyname then the old one will be released automatically.


If you allocate a new object, and you want to assign it to a object which is already "owned", then you must release that object and gain "ownership" of the new one.


No, the auto generated retain setter will call release if necessary, as long as you are using the setter (either directly or with dot notation). The setter would look something like this:

-(void)setObject:(id)newObject{
    if(newObject != myCurrentObject){
       [myCurrentObject release];
       myCurrentObject = [newObject retain];
    }
}

See Apple's Memory Management Programming Guide - Section Accessor Methods.


No, the generated setter method will release/autorelease the value previously reference by the ivar for the property.

Apple's Memory Management docs, although lengthy, are well worth a read for a better understanding.

Apple's Memory Management Documentation

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜