2

値の NSArray を取り、配列内の値の数に基づいて IN ステートメントで使用するプレースホルダーの文字列を返す FMDB のユーティリティ メソッドを作成しようとしています。

この文字列を作成するエレガントな方法が思い浮かびません。NSString ユーティリティ メソッドがいくつかありません。

// The contents of the input aren't important.
NSArray *input = @[@(55), @(33), @(12)];    

// Seems clumsy way to do things:
NSInteger size = [input count];
NSMutableArray *placeholderArray = [[NSMutableArray alloc] initWithCapacity:size];
for (NSInteger i = 0; i < size; i++) {
    [placeholderArray addObject:@"?"];
}

NSString *output = [placeholderArray componentsJoinedByString:@","];
// Would return @"?,?,?" to be used with input
4

1 に答える 1

4

これはどうですか?

NSArray *input = @[@(55), @(33), @(12)];

NSUInteger count = [input count];
NSString *output = [@"" stringByPaddingToLength:(2*count-1) withString:@"?," startingAtIndex:0];
// Result: ?,?,?

stringByPaddingToLength指定された文字列 (この場合は空の文字列) を指定された長さまで、 pattern の文字を追加して埋めます@"?,"

于 2013-10-15T15:01:47.537 に答える