0

我必须找到一种方法来检查(按一下按钮)文本字段中的文本是否存在于 xml 文件中。

我认为如果我将 xml 文件作为数组加载,那么我可以使用 for 循环来查看它是否与数组中的结果相同。

对于循环根本不实用,你能解释一下我如何为这类问题编写代码吗?

我希望如果整个数组中不存在该对象,则显示警报

谢谢

- (void)viewDidLoad
  {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

cose = [[NSArray alloc] initWithObjects:@"giovanni",@"giulio",@"ciccio",@"panzo", nil];

 }

- (void)didReceiveMemoryWarning
  {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

  -(IBAction)prova {

for (NSString *myElement in cose) {
    if ([myElement isEqualToString:textfield1.text]) {
        label1.text = textfield1.text;

    }
    else {

        UIAlertView *alertCellulare = [[UIAlertView alloc] initWithTitle:@"Attenzione!"       message:@"connessione assente" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];

        [alertCellulare show];
    }
}

}
4

2 回答 2

2

使用快速枚举:

-(IBAction)prova 
{
    BOOL present = NO;
    for (NSString *myElement in cose) {
        if ([myElement isEqualToString:textfield1.text]) {
            label1.text = textfield1.text;
            present = YES;
            break;
        }
    }

    if (!present){
        UIAlertView *alertCellulare = [[UIAlertView alloc] initWithTitle:@"Attenzione!"       message:@"connessione assente" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
        [alertCellulare show];
    }
}

基于块的枚举

-(IBAction)prova 
{
    __block BOOL present = NO;
    [cose enumerateObjectsUsingBlock:^(NSString *name, NSUInteger idx, BOOL *stop){

        if ([name isEqualToString:textfield1.text]) {
            label1.text = textfield1.text;
            present = YES;
            *stop = YES;
        }

     }];

    if (!present){
        UIAlertView *alertCellulare = [[UIAlertView alloc] initWithTitle:@"Attenzione!"       message:@"connessione assente" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
        [alertCellulare show];
    }
}
于 2013-02-09T14:05:16.100 回答
2

为什么不使用 For-In 循环(快速枚举)?

像这样的东西:

for (NSString *myElement in myArray) {
    if ([myElement isEqualToString:myTextField.text]) {
        // Do something
    }
}
于 2013-02-09T13:21:11.337 回答