How to replace current viewController with a new v

2019-02-11 04:56发布

问题:

I'm trying to replace my current viewController with a new one. I've been able to do this before but I'm having some issues with BAD_ACCESS.

This is the code that will run when I want to replace the current view with a new one.

(The function will be called using a local property "self.some_data" (nonatomic, retain))

-(void) labelSelected:(SomeDataObject*) some_data{ 
   SomeViewController *viewController = (SomeViewController*)[[ClassManager sharedInstance] viewControllerForClassIdentifier:@"com.somename" fromPlistFileName:@"iPhoneScreenList"];


   viewController.data = (NSObject*)some_data;
   [some_data retain];

   //[self.navigationController pushViewController:viewController animated:YES];

   UINavigationController *tempNavigationController = self.navigationController;

   [[self retain] autorelease];

   [tempNavigationController popViewControllerAnimated:FALSE];
   [tempNavigationController pushViewController:viewController animated:TRUE];
}

Here everything works fine. The issue is that if I release the new "viewController" it crashes. And if I choose:

[tempNavigationController popViewControllerAnimated:TRUE];

I get some really wierd behaviour where the controller never gets replace and I return to the rootController and the navigation bar has two layers of text on it.

And if I do this:

[tempNavigationController pushViewController:viewController animated:FALSE];

I get BAD_ACCESS and the application chrashes. It worked before but not anymore.

What am I doing wrong?

Thanks!

回答1:

Use category for controller replace:

//  UINavigationController+ReplaceStack.h


@interface UINavigationController (ReplaceStack)

- (void) replaceLastWith:(UIViewController *) controller;

@end

//  UINavigationController+ReplaceStack.m

#import "UINavigationController+ReplaceStack.h"

@implementation UINavigationController (ReplaceStack)

- (void) replaceLastWith:(UIViewController *) controller {
    NSMutableArray *stackViewControllers = [NSMutableArray arrayWithArray:self.viewControllers];
    [stackViewControllers removeLastObject];
    [stackViewControllers addObject:controller];
    [self setViewControllers:stackViewControllers animated:YES];
}

@end