IOS: presentmodalviewcontroller release

725 Views Asked by At

I use this code ti open a viewcontroller

self.secondViewController = [[SecondViewController alloc]initWithNibName:@"SecondViewController" bundle:nil];
[self presentModalViewController:self.secondViewController animated:YES];

[self.secondViewController release];

but if i use [self.secondViewController release]; when I call this code second time it crash because

[FirstViewController performSelector:withObject:withObject:]: message sent to deallocated instance 0x18a890

if I don't use it, it it's all ok, but in this situation when can I dealloc my secondviewcontroller? can you help me?

1

There are 1 best solutions below

0
On

From your code (self.secondViewController), my understanding is that you have declared secondViewController as a variable in your .h file, and @synthesize'd it in your .m file. If that's right, I would rather do the followings

if (self.secondViewController == nil)
    self.secondViewController = [[SecondViewController alloc] initWithNib:@"SecondViewController" bundle:nil];

[self presentModalViewController:self.secondViewController animated:YES];

and in your - (void)dealloc method, I would add [self.secondViewController release]; and in - (void)viewDidUnload I would add [self setSecondViewController:nil];.

The above code is with the assumption that you are not using ARC. If you are using ARC, I would revise my code as follows:

// Do not declare secondViewController as a variable in your .h file
// Instead, in storyboard, give it an identifier, e.g. secondViewController
// and 

SecondViewController *svc = [self.storyboard instantiateViewControllerWithIdentifier:@"secondViewController"];
[self presentModalViewController:svc animated:YES];
svc = nil;