如果发生以下两种情况之一,是否有办法执行一个代码?具体来说,我有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次。
如果其中一个或两个都为空,我怎么能让它只弹出一次?
答案 0 :(得分:2)
您可以使用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];
}
答案 1 :(得分: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];
}
答案 2 :(得分:0)
正如其他答案所指出的那样,你可以做一个或像这样的惰性评估:
if ([myTextField.text length] == 0 || [yourTextField.text length] == 0) {
延迟评估(||
而不是|
)只确保第二个条件只有在必须时才会运行。
请注意,这些内容会评估为BOOL,因此您可以利用并提供名称。例如:
BOOL eitherFieldZeroLength = ([myTextField.text length] == 0 || [yourTextField.text length] == 0);
if (eitherFieldZeroLength) {
虽然这对于当前案例来说是微不足道的,但使用中间变量可以增加代码的清晰度。