Print with stringWithFormat?


#1

Just wondering, on the Challenge, should we be able to print out the localized name using an instance of NSString created with the stringWithFormat: method? I guess basically I’m just wondering how you print an instance of NSString created with the stringWithFormat: method? Does NSLog work with this, or would you only use that to count the characters in the string or check if two strings were equal, etc?

Here is what I have (thanks to one of the posters on the Challenge thread for getting me started with his code, which clarified my thoughts on how to accomplish the initial task)

[code]
//create a NSHost object for this Mac
NSHost *thisComputer = [[NSHost alloc] init];

    //Get the name of this Mac
    NSString *thisComputerName = [thisComputer localizedName];
    
    //Print this Mac's name
    
    NSLog(@"This computer's localized name is %@.", thisComputerName);[/code]

Everything works fine up to here. It prints the name like it should. I was just wondering if, given the text, we should also be able to print using the stringWithFormat method.

[code] //use NSString stringWithFormat to print this Mac’s name

    NSString *longWayName = [NSString stringWithFormat:@"This computer's name is %@.", thisComputerName];
    
    NSLog(@"longWayName.");[/code]
    
    Of course, all this does is print out "longWayName". Am I trying to do something impossible, or just missing something? I suspect the latter.  :slight_smile:

#2

You can print any string at all, but it’s important to remember that, when inside a string literal, longWayName is no longer a variable, but just text. Just letters in a row. If you want to print out the value of an NSString, you must use the %@ substitution token inside the string literal passed to NSLog():

NLog(@" %@ ",longWayName);

#3

As Homer would say, “DOH!”

Thank you!

Why couldn’t I see that for myself? :blush:


#4

Btw.
Where can i find an overview for the different placeholders like the %@ substitution token?
In the last challenge i had to solve was a “%lu” placeholder and i could not remember what the “lu” stands for.

Thanks.


#5

http://developer.apple.com/library/mac/#documentation/cocoa/Conceptual/Strings/Articles/formatSpecifiers.html


#6

Thank you macintux! I have been similarly crazed trying to remember the formats.


#7

Thanks for the link - I’ve bookmarked this. :smiley: