开发者

Build string with variable number of keys and formats

开发者 https://www.devze.com 2023-03-08 20:15 出处:网络
I have an NSDictionary object that contains my data.I am passing in an array of key names and a display format for a string representation of my data.

I have an NSDictionary object that contains my data. I am passing in an array of key names and a display format for a string representation of my data.

[self displayMyDataWithTheseKeys:myKeyArray inThisFormat:myFormat];

where, for example,

myKeyArray = [NSArray arrayWithObjects开发者_StackOverflow社区: @"Key1", @"Key2", nil];

myFormat = [NSString stringWithString: @"%@ to the %@ degree"];

However, myFormat may change and the number of keys in the array may vary as well.

If the number of elements in the array was always 2, this would be trivial. However, how can I handle a variable number of elements?


There isn't really a built-in method for this, but it's relatively easy to parse format strings with NSScanner. Here's a simple example, it only handles %@ format specifiers, but as all elements in an NSArray are objects and not primitive types anyway, it shouldn't matter:

NSArray *myKeyArray = [NSArray arrayWithObjects: @"Key1", @"Key2", nil];
NSString *myFormat = [NSString stringWithString: @"%@ to the %@ degree"];

NSMutableString *result = [NSMutableString string];
NSScanner *scanner = [NSScanner scannerWithString:myFormat];
[scanner setCharactersToBeSkipped:[NSCharacterSet illegalCharacterSet]];
int i = 0;
while (![scanner isAtEnd]) {
    BOOL scanned = [scanner scanString:@"%@" intoString:NULL];
    if (scanned) {
        if (i < [myKeyArray count]) {
            [result appendString:[myKeyArray objectAtIndex:i]];
            i++;
        } else {
            //Handle error: Number of format specifiers doesn't 
            //match number of keys in array...
        }
    }
    NSString *chunk = nil;
    [scanner scanUpToString:@"%@" intoString:&chunk];
    if (chunk) {
        [result appendString:chunk];
    }
}


Use: stringByAppendingString

Here's an example on how to use it:

NSString *someString = @"String";

someString = [someString stringByAppendingString:[NSString stringWithFormat:@"%@",variable1]];
someString = [someString stringByAppendingString:[NSString stringWithFormat:@"%@",variable2]];
someString = [someString stringByAppendingString:[NSString stringWithFormat:@"%@",variable3]];

...and so on

If you have an array of keys which you want to put in a string:

NSString *string = @"And the keys are:\n";

    for(int i = 0; i < [array count]; i++)
    {
        NSString *thisKey = (NSString *)[array objectAtIndex:i];

        string = [string stringByAppendingString:[NSString stringWithFormat:@"Key number %d is %@",i,thisKey]];
    }
0

精彩评论

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

关注公众号