2

I am trying to make a utility method for FMDB which will take an NSArray of values and return a string of placeholders for use in an IN statement based on the number of values in the array.

I can't think of an elegant way of creating this string, am I missing some NSString utility method:

// 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
Dan Poltawski
  • 575
  • 4
  • 12

1 Answers1

4

What about this?

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

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

stringByPaddingToLength fills the given string (the empty string in this case) to the given length by appending characters from the pattern @"?,".

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382