tags:

views:

102

answers:

5

Is it a leak if I have a view controller and allocate the view like this:

self.view = [[UIView alloc] initWithFrame:frame];

Do I need to do something like this:

UIView *v = [[UIView alloc] initWithFrame:frame];
self.view = v;
[v release];
+2  A: 

Yes, the second one. Properties (self.view) retain their value usually.

Georg
+2  A: 

Yes, it's a leak. Your solution is correct, or you can do:

view = [[UIView alloc] initWithFrame:frame];

Where view is an instance variable. But it's not such good practice. As commented below, in a UIViewController view is a superclass property, so my code example is doubly wrong. However, the principle that self.variable is invoking setVariable:, and will observe the retain style of the property declaration is worth noting. In such cases you can directly assign to the instance variable above, which omits the retain - and makes such code a horror to maintain, which explains why Apple's Objective C 2.0 property syntactic sugar isn't universally admired.

Corrected because Georg was entirely correct.

Paul Lynch
Retaining an object more than releasing it has the effect of never deallocating it, that's called a memory leak.
Georg
view is a property from the super class of UIViewController. It is not the name of the ivar in that class so that code will not compile (it is _view for the ivar not view). Also you should never try to assign to the ivar of a super class from Apple.
Brandon Bodnár
A: 

This depends on the declaration of the view property. If it's not a (retain) property, then you're fine. If it is a retaining property, you must call release.

Adam Wright
A: 

There is a very simple rule for Objective-C memory management. If you've sent retain message, you've to send release also. I do not know exceptions with this rule is SDK itself.

Here we've alloc, that sends retain itself (always), so you have to release object somewhere. You can do it in dealloc or right here, after assigning it to self.view.

Alexander Babaev
+1  A: 

You need to read the Cocoa Memory Management Rules.

You obtained the object with +alloc. Therefore, according to the rules, you are responsible for releasing it. Your own solution is perfectly fine, or you could do:

self.view = [[[UIView alloc] initWithFrame:frame] autorelease];
JeremyP
That's the best solution, there's no chance to forget to release the object. However, autoreleasing is discouraged on the iPhone, because it uses more memory, which isn't a problem on a desktop, but on the iPhone it could be one.
Georg