Google Android Development Agency SASS

Tuesday 21 April 2009

Using % symbols in NSStrings

Normally, when you use the '%' symbol in an NSString, it's because you want to use a formatter to format some other variable and insert it into the results string.

For example

NSString *myString = [[NSString alloc] initWithFormat:@"Number : %d",5];

Would yield the string "Number : 5".

However, we've had a few cases where we need to output a percentage in a string, e.g. "50%". I spent a few minutes searching for complicated solutions, before it dawned on me that all you need to do is escape the % sign, thus telling the compiler that you don't want to invoke a formatter:

NSString *myStrWithPercent = [[NSString alloc] initWithFormat:@"%@%%",myNumber];

Yields "50%". The % sign escapes the second %. Simples!

No comments:

Post a Comment