开发者

releasing and reallocating a viewController?

I have a viewController that gets added to the current view like this:

theDetail = [[detailController alloc]  initWithNibName:@"detail" bundle:[NSBundle mainBundle]];
[self.view addSubview:theDetail.view];

Now - when the user closes this new view, I remove it from the superview.

The User might hit the button to show this view twice, though. But When I do this, the detailController gets alloced a second time and I get a retain-count of two.

When I release the detailView first, I get a n erro开发者_StackOverflow中文版r on the second click...

Anyone who can show me the right way to do this?


Why don't you use a navigation controller to load the view?


I found the solution - guess I REALLY should read the chapter about memory-management again (and again)...

The trick was to change the alloc-line to this:

self.theDetail = [[[detailController alloc]  initWithNibName:@"detail" bundle:[NSBundle mainBundle]] autorelease];

This exchanges the currently set «theDetail» with a new one, releasing the old one automagically (like the docs clearly state - one who can read has a clear advantage :)


I would also suggest using a navigation controller.

However - if you are sure you want to do this I would suggest that you store theDetail as a class-wide variable and then you can use something like the following:

if (theDetail == nil) {
    theDetail = [[detailController alloc]  initWithNibName:@"detail" bundle:[NSBundle mainBundle]];
    [self.view addSubview:theDetail.view];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜