objective-cmemory-managementretaincountalloc

Alloc a new objective C object to a retained property?


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.


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.