Wednesday, 19 November 2014

[iOS App] 'NSInvalidArgumentException', reason : unrecognized selector sent to Instance

I am going through iOS App development recently. I use modal segue to move from parent ViewController to child ViewController, as shown in the picture below.


When i return from child ViewController to parent ViewController.  There is an error.


2014-11-20 09:00:48.229 Heritage[64395:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[XYZContinentTableViewController topViewController]: unrecognized selector sent to instance 0x8c60050'

The error shows up when i have 3 level of ViewController, and specifically, from second level ViewController to root ViewController.

I found out the root cause. It is because the unwind segue

- (IBAction)unwindToRegion:(UIStoryboardSegue *)segue
{  }

is mixed up with prepareForSegue.

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    ....
}
   
To fix the error, in prepareForSegue, add the segue identifier checking. Make sure prepareForSegue is only processing the forward segue (In our case, the UserShowSegueCountry).

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    
    if ([[segue identifier] isEqualToString:@"UserShowSegueCountry"])
    {
    UINavigationController *nav = segue.destinationViewController;
    XYZCountryTableViewController *vcToPushTo = (XYZCountryTableViewController *)nav.topViewController;
        
    }
    

}