views:

68

answers:

2

I am building my own view in loadView of view controller. Just to check if I can release the view like below or there is anything else I will need to release it? I know framework will set it to nil once it requires to free up some memory.

- (void)loadView
{
    self.view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
    [self.view release];
        ...
}
+1  A: 

That looks a bit weird, I'd do this instead:

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
self.view = view;
[view release];

If you're using @property (retain) you don't have to worry about releasing it when it's set to nil e.g. self.view = nil;. However you should release it in dealloc.

jtbandes
So it's weird or incorrect? Do I have to `release` self.view in `dealloc` even if I don't overload `loadView`?
Michael
It's just weird. I suppose it works, I just wouldn't do it. You should release the view in dealloc no matter what; @synthesized properties don't do the final release for you.
jtbandes
That's really weird, because first of all memory management rule says if I don't own the object I don't have to release. In case if the self.view is created using nib file, then I don't own it, I guess. Second of all so far in Apple sample code I haven't seen releasing `self.view` in `dealloc` when view is created in Nib.
Michael
+1  A: 

The view property of a UIViewController will be released for you by the UIViewController itself. You are right however that when you create the view that you assign to a UIViewController you need to release it, but the way you are trying to do it is wrong. Either do what jtbandes suggest or simply:

self.view = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)] autorelease];
willcodejavaforfood