-4

2 つのいずれかが発生した場合に 1 つのコードを実行する方法はありますか? 具体的には、2 つの TextFields があり、それらのいずれかが空の場合、アクションが実行されたときに 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) 演算子を使用して、2 つの条件を 1 つの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

他の回答が指摘しているように、次のような遅延評価で or を実行できます。

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

遅延評価 (||の代わりに|) は、2 番目の条件が必要な場合にのみ実行されることを保証します。

これらは BOOL と評価されるため、これを利用して名前を付けることができます。例えば:

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

これは現在のケースでは些細なことですが、中間変数を使用するとコードが明確になります。

于 2012-05-05T15:21:05.810 に答える
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 に答える