Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Matthew Sinclair
595 PointsNSLog tokens
I'm getting all the logic pretty quickly, but I can never remember how to use NSLog properly.
Can someone break down what tokens refer to (with examples please), and explain what each token refers to and when to use them?
The videos don't really do this at all.
1 Answer
Oliver Duncan
16,642 PointsNSLog takes two arguments. The first must be an NSString, called the format string, containing text and a number of tokens. Tokens are prefixed with a % symbol, and correspond to the values of the next arguments you pass in to NSLog. The basic tokens are:
%@ - Objects, including NSStrings %d, %i - Signed integer (i.e. can be positive or negative) %f - Float or Double %p - Pointer, or memory address
Here's an example:
int main ()
{
NSString *name = @"Oliver";
int age = 28;
float weight = 159.5;
// Prints "Oliver is 28 years old and weighs 159.500000 pounds. His name is stored at memory address 0x7fff5fbff7c8"
NSLog(@"%@ is %d years old and weighs %f pounds. His name is stored at memory address %p", name, age, weight, &name);.
return 0;
}
Matthew Sinclair
595 PointsMatthew Sinclair
595 PointsThat is perfect @Oliver thanks!!
so to be sure I understand, you put the name of the variable ash the end of the NSLog (after the first ,) to tell the code before it what each token should reference? Referring to the "..., name, age, weight, &name); "
Oliver Duncan
16,642 PointsOliver Duncan
16,642 PointsExactly. The tokens act as placeholders, and the variables you pass in are substituted for them at runtime.
Matthew Sinclair
595 PointsMatthew Sinclair
595 PointsYou are fantastic!! Thanks man! (Also, thanks for the quick responses!!)