Creating a file name by adding two NSStrings
I am trying to load a file. The file name depends on a string stored in an array. In the following example, I would like to load tabRed.png. @"Red" is stored in an array.
This is what I tried:
UIImage *tabImage = [UIImage imageNamed:(@"tab%@.png", [self.currentNoteBook.tabColours objectAtIndex:0])];
But I only got "Red" as an output and not 开发者_StackOverflow中文版"tabRed.png". What am I doing wrong?
UIImage *tabImage = [UIImage imageNamed:[NSString stringWithFormat:@"tab%@.png", [self.currentNoteBook.tabColours objectAtIndex:0]]];
You need to use NSString stringWithFormat
. The comma operator (,
) does quite a different thing.
From Wikipedia,
In the C and C++ programming languages, the comma operator (represented by the token
,
) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type).
So when you write (@"tab%@.png", [self.currentNoteBook.tabColours objectAtIndex:0])
, it actually discards the first string and returns the object in array which is just "Red".
You need to make a new NSString for the file name. The string @"tab%@.png" won't automatically replace the placeholder for you. Use -stringWithFormat: as follows:
UIImage *tabImage = [UIImage imageNamed:[NSString stringWithFormat:@"tab%@.png", [self.currentNoteBook.tabColours objectAtIndex:0]]];
精彩评论