Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prepareForSegue : how can I set an if-condition?

This may be very rookie but...

I've set a segue between two ViewControllers in my Storyboard, with the identifier clickBtn.

Now I'm calling it this way in my code:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"clickBtn"])
    {
        if(conditionVerified)
        {
            SecondViewController *controller = (SecondViewController *)segue.destinationViewController;
            [controller setManagedObjectContext:self.managedObjectContext];
        }
        else
        {
            // If I enter here I get the error below
        }
    }
}

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'Link''

In fact I don't want to do this transition if I enter the else-statement. How to do so?

like image 757
Rob Avatar asked Nov 05 '13 21:11

Rob


2 Answers

To optionally suppress a transition, implement

- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender

and return YES or NO, depending on your condition. In your example:

- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender
    if ([identifier isEqualToString:@"clickBtn"])  {
        return conditionVerified;
    } else {
        return YES;
    }
}

In prepareForSegue: it is "too late" to suppress the transition.

like image 105
Martin R Avatar answered Oct 04 '22 22:10

Martin R


Rather than having the button perform the segue have it call a method like the following.

-(IBAction)mySegueButtonMethod:(id)sender
{
   if(conditionVerified){
      [self performSegueWithIdentifier:@"clickBtn" sender:sender];
   }
   else{
        // do not perform segue and do other relevant actions.
   }
}

The error you are seeing is because i am assuming controller is calling something that needs context manager not to be nil.

You can't really stop the segue from occurring once you are in the method prepareForSegue as it will always perform the segue at the end of the method.

like image 31
Ben Avery Avatar answered Oct 04 '22 21:10

Ben Avery