Search code examples
iosseguensnotificationcenter

Can't perform segue in other class in iOS 5?


I'm new in IOS development. I'm trying to perform a segue of ViewController1 on other class and I'm using the NSNotificationCenter to access the segue method to other class. The segue is working when I'm calling it inside the ViewController1 but when I'm calling it to other class that give me an error of

NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 
'NSBundle </Users/dev03/Library/Application Support/iPhone Simulator/7.0.3/Applications/9Bsf3724-557D-40F4-A369-F58A31234120/MedsRUs.app> 
(loaded)' with name 'UIViewController-LTT-QY-pu7' and directory 'Main_iPhone.storyboardc

In my ViewController1 I have this:

- (void)viewDidLoad{
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(goToSelectItem:) name:@"performSegueSoldToToSelectItem" object:nil];

}

-(void)goToSelectItem:(NSNotification *)Notif{

    [self performSegueWithIdentifier:@"soldTotoSelectItem" sender:self];
 }

And this what I did on the other class to call the method goToSelectItem

-(void)nextController{

    [[NSNotificationCenter defaultCenter] postNotificationName:@"performSegueSoldToToSelectItem" object:nil];
}

Solution

  • Another option is to use blocks and background thread. The block of code after dispatch_async is executed on a background thread and does not block UI. When the code is completed you can simply perform the segue, this time on main thread.

    #import "ViewController.h"
    #import "MyNSObject.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        MyNSObject *myNSObject = [[MyNSObject alloc] init];
    
        // do something with myNSObject on a background thread
    
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_async(queue, ^{
    
            [myNSObject loopFinished];
    
            dispatch_async(dispatch_get_main_queue(), ^{
    
                // perform on main
                [self performSegueWithIdentifier:@"mySegueIdentifier" sender:self];
            });
        });
    }
    
    @end
    

    All UI updates would need to be wrapped with dispatch_async(dispatch_get_main_queue(), ^{}, but I assume you are not doing any UI related things in your NSObject class.

    Also notice unwind segues are new in iOS6 I believe, so for iOS5 you would need to perform regular segues or present new view controllers in code with push or modally.