views:

26

answers:

3

Hi Forum

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 error on the second click...

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

A: 

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

alecnash
don't ask this question - just don't ask it... :)
Swissdude
why did I say something wrong?
alecnash
A: 

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 :)

Swissdude
A: 

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];
}
rhodesy22
I would really suggest doing this rather than an autorelease. Initialising an object takes processing power, so if you don't have to init a new object then don't...
rhodesy22