开发者

How do you join an NSArray of [Number numberWithChar: c]'s into an NSString?

When I use componentsJoinedByString, I just get a long string of digits.

Edit: I realize this task is confusing. Why on earth would anyone populate an NSArray with NSNumbers if they wanted an NSString? The answer is that I'm writing an extensible unit test framework. The basic functions genNum, genBool, and genChar generate NSNumbers with random int, BOOL, and char values respectively. Then there's genArray which generates a random array using a specified generator. So to construct a random NSString, one would run genArray using the genChar generator, and transform the resulting NSArray into an NSString.

The characters are only stored as NSNumbers instead of chars due to a technicality: genArray accepts a block and calls the block开发者_开发问答 100-odd times to populate the NSArray. Blocks must hold ObjC objects; not primitive types.

So the question remains: How do you join an NSArray of [NSNumber numberWithChar: c]'s into an NSString?


componentsJoinedByString joins the array elements into a string with the separator character between them. The array elements are converted to strings (if not already NSString" using the description method. If you have n array of NSNumbers I would expect an interesting result.


Why not fill your array with [NSString stringWithCharacters:c length:1]? Then componentsJoinedByString: ought to work. (Check the docs on stringWithCharacters:length:; the above is just for illustration. You might have to use &c, for example.)


+ (NSString *) genString {
    NSArray* arr = [self genArray: ^() { return [ObjCheck genChar]; }];

    NSMutableString* s = [NSMutableString stringWithCapacity: [arr count]];

    int i;
    for (i = 0; i < [arr count]; i++) {
        [s appendString: [NSString stringWithFormat: @"%c", [[arr objectAtIndex: i] charValue]]];
    }

    return s;
}


+ (id)genString {
    NSArray *chars = [self genArray:^{ return [ObjCheck genChar]; }];

    if ([chars count] == 0) {
        return @"";
    }

    unichar *buffer = malloc(sizeof(unichar) * [chars count]);

    [chars enumerateObjectsUsingBlock:^(NSNumber *num, NSUInteger idx, BOOL *stop) {
        buffer[idx] = (unichar)[num charValue];
    }];

    return [[[NSString alloc] initWithCharactersNoCopy:buffer length:[chars count] freeWhenDone:YES] autorelease];
}

This particular solution will assume chars >127 should be treated as unicode codepoints (which basically means, for char-sized values, as ISO-8859-1). It also avoids copying the buffer when creating the resulting string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜