Search code examples
iosobjective-cstoryboardreleasedealloc

dealloc after instantiateViewControllerWithIdentifier


i have a problem:

ExploreViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"ProfileViewController"];
vc.id_from = post.user_id;
[self.navigationController pushViewController:vc animated:YES];

As you can see, i instantiate the viewController and push it into navigationController. vc, should be autorelease , but dealloc method is never called.

So, if i release the view controller after pushed it:

ExploreViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"ProfileViewController"];
vc.id_from = post.user_id;
[self.navigationController pushViewController:vc animated:YES];
[vc release];

dealloc method is called when i pop the view controller, but if i execute again the code above, dealloc is immediately called and app crash because others objects don't found vc.

So, if i don't release it, the memory is increasingly busy.

Thank you everybody!


Solution

  • It's not released because when you:

    [self.navigationController pushViewController:vc animated:YES];
    

    The UINavigationController has a reference to the vc. So basically you have 2 references to it:

    self.navigationController + ExploreViewController *vc = 2
    

    At the end of the method you have one:

    self.navigationController = 1
    

    Once you pop the vc from the UINavigationController, the vc should be released and the dealloc method called. Another thing, you shouldn't call release on object you don't own. In this case instantiateViewControllerWithIdentifier returns an auto-release object.