objective-c - 在 NSMutableArray 中比较字符串的问题

标签 objective-c ios xcode

我编写了一个循环遍历按钮数组的方法,并检查字符串是否等于数组中的任何按钮标题,但它不起作用,尽管传递给该方法的字符串等于数组中的一些字符串,这是我的代码:

-(void)checkDuplicatesInSection:(NSString*)btnLabel
{
    for (UIButton* btn in self.test) {
        if([btnLabel isEqualToString:btn.titleLabel.text])
        {
            NSLog(@"Inside check Dublicates--->Title Existed");
        } else {
            NSLog(@"Inside check Dublicates--->Title Not Existed");
        }
    }
}

// self.test---> it's an array contains group of buttons
// btnLabel----> it's a string passed to that method

我不明白的是,为什么当我运行该程序时,我同时得到 Inside check Dublicates--->Title Existed"Inside check Dublicates--->Title Not存在

最佳答案

代码:

if([btnLabel isEqualToString:btn.titleLabel.text])
{
    NSLog(@"Inside check Dublicates--->Title Existed");
} else {
    NSLog(@"Inside check Dublicates--->Title Not Existed");
}

会被执行多次,因为它在for循环中。这就是为什么在运行代码时会打印两个日志的原因。

要测试 self.test 是否包含字符串 btn.titleLabel.text 您应该将代码修改为:

-(void)checkDuplicatesInSection:(NSString*)btnLabel
{
    BOOL found = NO;
    for (UIButton* btn in self.test) {
        if([btnLabel isEqualToString:btn.titleLabel.text]) {
            found = YES;
            break;
        }
    }
    if (found) {
        NSLog(@"Inside check Dublicates--->Title Existed");
    } else {
        NSLog(@"Inside check Dublicates--->Title Not Existed");
    }
}

或者您可以简单地使用方法-containsObject: *:

    -(void)checkDuplicatesInSection:(NSString*)btnLabel
{
    BOOL found = [self.test containsObject:btn.titleLabel.text];

    if (found) {
        NSLog(@"Inside check Dublicates--->Title Existed");
    } else {
        NSLog(@"Inside check Dublicates--->Title Not Existed");
    }
}

* 即使 btn.titleLabel.text 是一个 NSString 也能正常工作。

关于objective-c - 在 NSMutableArray 中比较字符串的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9854815/

相关文章:

ios - Visual Studio 2015 Cordova iOS 构建不使用 build.json 参数

ios - 核心数据和可转换检索图像

ios - 从父类获取属性

ios - SKTextureAtlas 和 3x 图像

ios - phonegap 应用程序中的随机白色闪光

iOS:ARC 不允许使用 CFTypeRef

ios - SpriteKit `sprite.atlas` 包何时以及如何压缩/优化?

iphone - 进行移动和服务器同步的最佳方式是什么?

ios - 有没有办法知道 iOS 键盘是否真的被隐藏了(被用户解雇了)?

ios - 在不同的方向上实现像素完美的背景图像