componentsSeparatedByString无法将字符串与值进行比较

时间:2012-11-11 18:58:50

标签: objective-c arrays string

当我使用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”。如果你能为我解决这个问题,那将是一个很好的帮助。谢谢:)

3 个答案:

答案 0 :(得分:3)

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

[item isEqualToString:@"1"]

答案 1 :(得分: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
}

答案 2 :(得分:0)

运算符==比较两个 - 整数,浮点数,引用等。当你写:

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

您在询问objectAtIndex:返回的引用是否等于文字表达式@"1"返回的引用,这不太可能是真的或者您是什么愿望。

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

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

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

相关问题