4

In Objective-C I see

[object retain];

What does sending a retain message to an object mean and why would I use it?

Adil Hussain
  • 30,049
  • 21
  • 112
  • 147
bobobobo
  • 64,917
  • 62
  • 258
  • 363
  • Related - and even more confusing are statements like.. `#warning BLAHBLAHBLAH returns retained object on non-IOS platforms`. which results in an analyzer warning like.. `Potential leak of an object stored into 'BLAHBLAHBLAH'` Great, now what?!? – Alex Gray Jun 26 '13 at 15:02

3 Answers3

11

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];
Hiren
  • 12,720
  • 7
  • 52
  • 72
ahmet emrah
  • 1,858
  • 2
  • 15
  • 22
  • 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 Nov 10 '09 at 00:48
  • 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 Nov 10 '09 at 18:41
6

It ups the reference count on the object in question.

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

Community
  • 1
  • 1
Matt Dillard
  • 14,677
  • 7
  • 51
  • 61
3

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
  • 234,037
  • 30
  • 302
  • 389