我是iOS新手,仍在学习如何做事的正确方法。刚刚开始研究的另一个问题是,如何停止执行某个方法,基于条件并返回调用代码?通常在PHP中,我只返回true
/ false
,或抛出异常,而不是在嵌套条件中隐藏大量代码,但在iOS中,我不允许从带有IBAction返回签名。
处理这个sitch的首选方法是什么?
- (IBAction)submitCode:(id)sender
{
if ([codeEntry.text length] == 0) {
UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Form Validation" message:@"No code entered, please try again."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[message show];
// IOS not allowing this
return NO;
}
// Prefer not to wrap the rest of the logic in an else, rather just cease
// execution and return back to calling code
NSLog(@"I would have submitted!");
}
答案 0 :(得分:1)
只需使用
return;
这将停止执行当前方法。
由于IBAction
秘密地typdef
加入void
,因此您无法返回任何内容。没有什么是没有的,所以只需使用return;
。
答案 1 :(得分:1)
您需要致电return;
,而不是return NO;
。
IBAction
确实是void
。这意味着该方法没有返回值。