prepareForSegue:我怎么能设置一个if条件?

这可能是新手,但…

我在Storyboard两个ViewControllers之间设置了一个segue,标识符为clickBtn

现在我在我的代码中这样调用它:

 - (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 } } } 

终止应用程序由于未捕获的exception'NSInvalidArgumentException',原因:'+ entityForName:nil是不合法的NSManagedObjectContext参数search实体名称'链接''

事实上,如果我inputelse语句,我不想​​做这个转换。 怎么做?

有没有button执行segue有它调用像下面的方法。

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

你看到的错误是因为我假设控制器正在调用一些需要上下文pipe理器的东西不是零。

一旦你在prepareForSegue方法中,你不能真正停止发生,因为它总是在方法结束时执行segue。

要有select地禁止转换,请执行

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

并根据您的情况返回YESNO 。 在你的例子中:

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

在准备prepareForSegue:压制转型是“太迟了”。

您应该为此重构不同的代码。 实现shouldPerformSegueWithIdentifier像下面这样使用shouldPerformSegueWithIdentifier实现:

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

如果条件未被validation,则会阻止执行segue“clickBtn”,即conditionVerified为false。 现在使用:

 -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([[segue identifier] isEqualToString:@"clickBtn"] && conditionVerified) { //just a double checking SecondViewController *controller = (SecondViewController *)segue.destinationViewController; [controller setManagedObjectContext:self.managedObjectContext]; } } 

只有当shouldPerformSegueWithIdentifier返回YES(true)时,才会准备执行。 所以如果条件没有被validation,你将永远不会面对任何意想不到的过渡。

希望能帮助到你。

试试这个。它对我有用!

 - (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender { if ([identifier isEqualToString:@"Login"] && condition ) { return YES; } else if ([identifier isEqualToString:@"SignUp"]) { return YES; } else { UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"OOPS!!" message:@"Incorrect Username Or Password" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK",nil]; return NO; } } return YES; } 

更好的方法是使用方法shouldPerformSegueWithIdentifier如下所述: https : shouldPerformSegueWithIdentifier