ios - for循环与数组ios

标签 ios objective-c cocoa-touch for-loop

<分区>

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

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

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];
    }
}

}

最佳答案

快速枚举:

-(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];
    }
}

基于 block 的枚举

-(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];
    }
}

关于ios - for循环与数组ios,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14788533/

上一篇:ios - 重构 iOS 代码 : Decreasing the number of lines of code

下一篇:ios - 确保不同部分的代码在 iOS 的后台队列中运行

相关文章:

ios - 使用 IBM Worklight 在 ios 中列出可用网络

iphone - 从框架加载 nib 文件

objective-c - Sprite 效应ipad

ios - 核心动画 : Pause before autoreversing?

cocoa-touch - 在没有 UITabBar 或 UINavigationBar 的 iOS 中编排多个 View 的最佳方式?

ios - NSDate 谓词抛出 'Unable to parse the format string' 错误

ios - 是否可以使用通过代码完成的 sqlite 查询来访问核心数据数据库?

iphone - 如何在iOS中将JSON字符串保存到Sqlite的一个字段中?

ios - 绘制两种不同颜色的 map View 图钉

ios - 对类别中的私有(private)方法进行单元测试?