Reputation: 67254
In Objective-C I see
[object retain];
What does sending a retain
message to an object mean and why would I use it?
Upvotes: 4
Views: 3790
Reputation: 1858
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];
Upvotes: 11
Reputation: 237060
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.
Upvotes: 3
Reputation: 14853
It ups the reference count on the object in question.
See this post for more details about reference counting in Objective C.
Upvotes: 6