David542
David542

Reputation: 110093

How to do NSLog with variable

What should be the correct format of the below to print *newString ?

NSString *newString = @"Hello this is a string!";
NSLog(@newString);

Upvotes: 2

Views: 1350

Answers (2)

Can Poyrazoğlu
Can Poyrazoğlu

Reputation: 34780

The @ symbol is just a shorthand for specifying some common Objective-C objects. @"..." represents a string (NSString to be specific, which is different from regular C strings), @[...] represents an array (NSArray), @{...} represents a dictionary (NSDictionary).

On the first line, you've already specified a NSString object using the @ sign. newString is now an NSString instance. On the second line, you can just give it's variable name:

NSLog(newString);

You could theoretically just give the variable name, but it is a dangerous approach. If newString has any format specifiers, your app may crash/mess up (or access something that it shouldn't be accesing) because NSLog would try to read the arguments corresponding to the format specifiers, but the arguments don't exist. The safe solution would be NSLog(@"%@", newString);. The first argument to NSLog is now hard-coded and can't be changed. We now know that it will expect a single argument, that we are providing that argument, newString, so we are safe.

Because you've already specified a string and just passing that instance to NSLog, you don't need the @ sign again.

Upvotes: 0

Gabriele Petronella
Gabriele Petronella

Reputation: 108091

NSLog works pretty much as a C printf, with the addition of the %@ string format specifier, which is meant for objects. Being NSString an object, %@ is the right format to use:

NSString *newString = @"Hello this is a string!";
NSLog(@"%@", newString);

For as tempting as it can look, NEVER do

NSLog(newString); //NONONONONO!

since it's a terrible practice that may lead to unexpected crashes (not to mention security issues).

More info on the subject: Warning: "format not a string literal and no format arguments"

Upvotes: 3

Related Questions