tags:

views:

124

answers:

3

In objective-c you see

[object retain] ;

What does sending a retain message to an object mean and why would you use one?

+3  A: 

It ups the reference count on the object in question.

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

Matt Dillard
+4  A: 

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];

ahmet emrah
How do you identify if an object (such as an array) will be autoreleased once your variable handle to it goes out of scope?
bobobobo
ok. other than the ones w alloc/init, copy, or retain, any object assignment will give you an autoreleased object instance:myString = [NSstring stringWith...]myArray = [NSArray arrayWith....]myImage = [UIImage image...]all give you autoreleased instances, so these object will be autoreleased at some time you dont control. to take control, you may call retain on them and release it safely after you are done.
ahmet emrah
+1  A: 

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.

Chuck
+10 up votes, if only I could.
Chris Johnsen