views:

648

answers:

2

I have a fairly simple question concerning NSString however it doesn't seem to do what I want.

this is what i have

NSString *title = [NSString stringWithformat: character.name, @"is the character"];

This is a line in my parser takes the charactername and inserts in into a plist , however it doesn't insert the @"is the character" is there something I'm doing wrong?

A: 

stringWithFormat takes a format string as the first argument so, assuming character.name is the name of your character, you need:

NSString *title = [NSString stringWithformat: @"%s is the character",
    character.name];

What you have is the character name as the format string so, if it's @"Bob" then Bob is what you'll get. If it was "@Bob %s", that would work but would probably stuff up somewhere else that you display just the character name :-)

Note that you should use "%s" for a C string, I think "%@" is the correct format specifier if character.name is an NSString itself.

paxdiablo
mmm thank you for your quick reply, however this doesn't seem to be the case. I tried it but knew it would fail since I already tried NSString *title = [NSString stringWithformat: @"is the character", character.name]; And then it seems to take the "is the character" perfectly.
That's because you don't have the "%s" in there (it should be @"%s is the character", not @"is the character"). When you put the "%s" into your format string, it will be replaced with the string contained in next argument (i.e., character.name). See also update if character.name is an NSString rather than a C string.
paxdiablo
The code example should probably use %@ instead of %s. In my experience C strings are very rarely used in Cocoa, but %@ will work for any NSObject.
Tom Dalling
ok super thnx guys .. it works 1
+2  A: 

Your code is wrong. It should be :

NSString *title 
    = [NSString stringWithformat:@"%@ is the character", character.name];

assuming that character.name is another NSString.

Read the Formatting String Objects paragraph of the String Programming Guide for Cocoa to learn everything about formatting strings.

IlDan
Thanks however it doesn't seem to workeven if i do this , it just fails to add the second string.NSString *title = [NSString stringWithformat:@"%s is the character", @"%s is the character two"];