开发者

What does the retain message mean?

In Objective-C I see

[object retain];

What does sending a retain message to an object mean and why would I 开发者_如何学运维use it?


Basically it is used to take 'ownership' on an object, i.e. by calling retain, the caller takes the responsibility of handling memory management of that object.

Two very common usages of the top of my hat are:

1- you initiate an object with auto memory managed methods, but want it to hang around some time : someObject = [[someArray objectAtIndex:someIndex] retain], without retain the object will be autoreleased at some time you don't control.

2- you initiate an object by passing somePointer to it, you do your memory management and call release on somePointer, and now somePointer will hang around until the newly initiated object releases it, the object calls retain on somePointer and now owns it.

-(id) initWithSomePointer:(NSObject *)somePointer_{

if(self = [super init])

somePointer = [somePointer_ retain];

return self;

}

..

..

[somePointer release];


It ups the reference count on the object in question.

See this post for more details about reference counting in Objective C.


Read Apple's memory management guide for a complete and pretty simple explanation of everything to do with Cocoa memory management. I strongly recommend reading that rather than depending on a post on Stack Overflow.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜