문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top