1

当我使用 xcode 中的 componentsSeparatedByString 函数将字符串分成数组时,我遇到了这个问题。

所以我从这个字符串创建一个数组:

theDataObject.stringstick = @"1 0 0 0 0 0 0 0 1 0 1 1 1 0 0 0";

stickerarray = [[NSMutableArray alloc] initWithArray:[theDataObject.stringstick componentsSeparatedByString:@" "]];

所以在我看来,我期望:

stickerarray = {@"1",@"0",@"0",@"0",@"0",@"0",@"0",@"0",@"1",@"0",@"1",@"1",@"1",@"0",@"0",@"0"}

所以当我通过 if 语句检查索引是否 = 1

for ( int n = 0; n <= 15; n++) {
    if ([stickerarray objectAtIndex:n] == @"1") {
        NSLog(@"this works %i", n);
    } else {
                NSLog(@"this did not work on %@", [stickerarray objectAtIndex:n]);
    }
}

这就是我得到的:

 this did not work on 1
 this did not work on 0
 this did not work on 0
 this did not work on 0
 this did not work on 0
 this did not work on 0
 this did not work on 0
 this did not work on 0
 this did not work on 1
 this did not work on 0
 this did not work on 1
 this did not work on 1
 this did not work on 1
 this did not work on 0
 this did not work on 0
 this did not work on 0

当我发现这不起作用时,我很惊讶,所以我尝试应用一些查询:

NSLog(@"ns array value of %@",[stickerarray objectAtIndex:2] );
ns array value of 0

NSLog(@"%@", stickerarray);
(
1,
0,
0,
0,
0,
0,
0,
0,
1,
0,
1,
1,
1,
0,
0,
0

)

NSLog(@"%@", theDataObject.stringstick);
1 0 0 0 0 0 0 0 1 0 1 1 1 0 0 0

当我在 if 语句中比较它时,我怀疑它是 @"1" 。如果你能帮我解决这个问题,那就帮大忙了。谢谢 :)

4

3 回答 3

3

您对 componentsSeparatedByString 的使用可能有效,但您的测试存在缺陷。在objective-c 中你需要使用NSString 的isEqualToString。"==" 比较两个字符串的指针,只有当它们指向同一个字符串实例时才会相等。你应该使用更多类似的东西:

[item isEqualToString:@"1"]
于 2012-11-11T19:06:54.760 回答
1

您没有正确比较字符串..

for ( int n = 0; n <= 15; n++) {
    if ([[stickerarray objectAtIndex:n] isEqualToString:@"1"]) {
        NSLog(@"this works %i", n);
    } else {
        NSLog(@"this did not work on %@", [stickerarray objectAtIndex:n]);
    }
}

额外的建议..你也应该以不同的方式循环你的数组。(一个块将是最快的)

for (id obj in stickerarry){
//do stuff with obj
}
于 2012-11-11T19:10:21.820 回答
0

运算符==比较两个- 整数、浮点数、引用等。当您编写时:

[stickerarray objectAtIndex:n] == @"1"

您在问由返回的引用objectAtIndex:是否等于由文字表达式返回的引用@"1",这不太可能是真实的或您想要的。

要比较对象实例是否代表相同的值,请使用以下方法isEqual:

[[stickerarray objectAtIndex:n] isEqual:@"1"]

这适用于任何类型的对象,对于通常更常用的字符串isEqualToString:- 它产生完全相同的答案,但速度更快一些。

于 2012-11-11T19:12:59.943 回答