3

文字列の配列を取得し、各アイテムを取得して文字列形式に変換しようとしています。リストされた配列値を別の文字列に連結する必要があるため、これを行うためのメソッドを作成しました。何らかの理由で、配列値を正しくリストすることができず、空白の文字列が返されます。

- (NSString*)listParameters:(NSArray*)params
{
NSString *outputList = @"";

if (params) {
    for (int i=0; i<[params count]; i++) {
        NSLog(@"%@",[params objectAtIndex:i]);
        [outputList stringByAppendingString:[params objectAtIndex:i]];
        if (i < ([params count] - 1)) {
            [outputList stringByAppendingString:@", "];
        }
    }
}
NSLog(@"outputList: %@", outputList);
return outputList;
}

最初のlogステートメントは適切に文字列を返します(したがって、配列には間違いなく文字列があります)が、2番目のlogステートメントは「outputList:」のみを返します。

outputListを、機能しなかった単なる空の文字列以上のものとして開始させてみました。また、文字列に割り当て[params objectAtIndex:i]てから追加しようとしましたが、どちらも機能しませんでした。

ここで明らかな何かが欠けているように感じますが、それを機能させることができません。

この文字列の配列をコンマで区切った単一の文字列に出力するにはどうすればよいですか?

4

3 に答える 3

8

appendString メソッドの代わりにNSMutableStringを使用することをお勧めします。NSString は不変です。

- (NSString*)listParameters:(NSArray*)params
{
    NSMutableString *outputList = [[NSMutableString alloc] init];

    if (params) {
        for (int i=0; i<[params count]; i++) {
            NSLog(@"%@",[params objectAtIndex:i]);
            [outputList appendString:[params objectAtIndex:i]];
            if (i < ([params count] - 1)) {
                [outputList appendString:@", "];
            }
        }
    }

    NSLog(@"outputList: %@", outputList);
    return outputList;
}
于 2013-02-11T20:50:24.987 に答える
4

の結果を割り当てて、[outputList stringByAppendingString:[params objectAtIndex:i]][outputList stringByAppendingString:@", "]戻す必要がありoutputListます。

代わりにNSMutableStringのインスタンスを使用している場合はoutputList、そのループ内に多数の自動解放されたオブジェクトを作成するため、さらに良いでしょう。

于 2013-02-11T20:44:05.303 に答える
1

試す:

outputList = [outputList stringByAppendingString:@", "];

stringByAppendingString は新しい文字列を返すことで機能するため

于 2013-02-11T20:47:10.793 に答える