-4

如果发生两件事中的任何一件,有没有办法执行一个代码?具体来说,我有 2 个 TextField,如果其中任何一个为空,我想在执行操作时弹出 UIAlertView。我可以设置

if ([myTextField.text length] == 0) {
    NSLog(@"Nothing There");
    UIAlertView *nothing = [[UIAlertView alloc] initWithTitle:@"Incomplete" message:@"Please fill out all fields before recording" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
    [nothing show];
    [nothing release];
}
if ([yourTextField.text length] == 0) {
    NSLog(@"Nothing For Name");
    UIAlertView *nothing = [[UIAlertView alloc] initWithTitle:@"Incomplete" message:@"Please fill out all fields before recording" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
    [nothing show];
    [nothing release];
}

但如果两者都为空,则会弹出该语句 2 次。

如果其中一个或两个都为空,我怎样才能让它只弹出一次?

4

3 回答 3

2

您可以使用(or) 运算符将这两个条件组合成一条if语句。||

if (([myTextField.text length] == 0) || ([yourTextField.text length] == 0)) {
    NSLog(@"Nothing There");
    UIAlertView *nothing = [[UIAlertView alloc] initWithTitle:@"Incomplete" 
                                                      message:@"Please fill out all fields before recording" 
                                                     delegate:self 
                                            cancelButtonTitle:@"Ok" 
                                            otherButtonTitles:nil];
    [nothing show];
    [nothing release];
}
于 2012-05-05T15:02:16.497 回答
0

使用复合条件

if (([myTextField.text length] == 0) || ([yourTextField.text length] == 0))) {
    NSLog(@"Nothing There");
    UIAlertView *nothing = [[UIAlertView alloc] initWithTitle:@"Incomplete" message:@"Please fill out all fields before recording" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
    [nothing show];
    [nothing release];
}
于 2012-05-05T15:01:40.413 回答
0

正如其他答案指出的那样,您可以像这样进行或使用惰性评估:

if ([myTextField.text length] == 0 || [yourTextField.text length] == 0) {

惰性评估(||而不是|)只是确保第二个条件仅在必须运行时才运行。

请注意,这些东西的计算结果为 BOOL,因此您可以利用这些东西并给它们命名。例如:

BOOL eitherFieldZeroLength = ([myTextField.text length] == 0 || [yourTextField.text length] == 0);
if (eitherFieldZeroLength) {

虽然这对于当前情况来说是微不足道的,但使用中间变量可以增加代码的清晰度。

于 2012-05-05T15:21:05.810 回答