Question

Sorry for asking a totally basic question, but if I have a synthesized property that is retained.

 self.myProperty = [[NSObject alloc] init];

will cause a memory leak?

So am I correct in thinking that I need to do

self.myProperty = [[NSObject alloc] init];
[self.myProperty release];

in order to balance? Because that seems dumb.

Was it helpful?

Solution

Standard practice would be to use autorelease in that situation. So:

self.myProperty = [[[NSObject alloc] init] autorelease];

This is because init returns a retained object, and since your property also retains it, you'll have to release it.

Edited to add: @walkytalky makes a good point in the comments that it is actually alloc that retains the object, init just returns it.

OTHER TIPS

Here is a thread that you will find helpful.

You are correct. Without ARC, any property that is retained needs to be released as well.

You can also do:

self.myProperty = nil;

From the docs:

retain

Specifies that retain should be invoked on the object upon assignment.

The previous value is sent a release message.

Another (more verbose) technique is to do:

NSObject *o = [[NSObject alloc] init]; //retain count 1
self.myProperty = o;                   //retain count 2
[o release];                           //retain count 1

Personally though, I'd probably just use autorelease as in the first example above.

With ARC enabled, xcode will handle alle the memory management. When not using ARC be sure to release it in the dealloc method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top