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 を使用する必要があります。"==" は 2 つの文字列のポインターを比較し、それらが文字列の同じインスタンスを指している場合にのみ等しくなります。次のようなものを使用する必要があります。

[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

この演算子は、整数、浮動小数点数、参照などの2 つの値を==比較します。次のように記述します。

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

によって返される参照がリテラル expression によって返される参照objectAtIndex:と等しいかどうかを尋ねていますが@"1"、これが真または希望するものである可能性はほとんどありません。

オブジェクト インスタンスが同じ値を表しているかどうかを比較するには、次のメソッドを使用しますisEqual:

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

これは、あらゆる種類のオブジェクトで機能します。文字列の場合、通常はより一般的に使用されますisEqualToString:。まったく同じ答えが得られますが、少し高速です。

于 2012-11-11T19:12:59.943 に答える