2

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

NSString *newString = @"Hello this is a string!";
NSLog(@newString);
David542
  • 104,438
  • 178
  • 489
  • 842

2 Answers2

3

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"

Community
  • 1
  • 1
Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
0

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.

Can Poyrazoğlu
  • 33,241
  • 48
  • 191
  • 389
  • 1
    This is potentially insecure and you shouldn't get in this habit. `NSLog(@"%@", newString);` is correct. See http://en.wikipedia.org/wiki/Uncontrolled_format_string. – Aaron Brager Oct 05 '13 at 19:33
  • wouldn't NSLOG handle this? it doesn't accept regular C strings anyway, you need to provide an NSString, which should be controlled anyway. – Can Poyrazoğlu Oct 05 '13 at 19:39
  • 2
    What if `newString` were @"%@ %@ %@ %@ %@ %@". **BOOM** is what. – bbum Oct 05 '13 at 19:57