1

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks however it doesn't seem to work even 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"];
You need to use $@ if passing an NSString, or %s if passing a C string.
0

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.

3 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.