Pablo
Pablo

Reputation: 29529

Proper way to release view in UIViewController

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];
        ...
}

Upvotes: 0

Views: 2023

Answers (2)

willcodejavaforfood
willcodejavaforfood

Reputation: 44103

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];

Upvotes: 2

jtbandes
jtbandes

Reputation: 118781

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.

Upvotes: 4

Related Questions