0

Lets say I just want to NSLog a string - can someone explain the difference between: Code 1:

NSString *testString;  
testString = [[NSString alloc] init];  
testString = @"Here's a test string in testString!";  
NSLog(@"testString: %@", testString); 

and Code 2:

NSString *testString = @"Here's a test string in testString!";
NSLog(testString)

Let's assume I am using ARC. Thanks

Sam Heather
  • 1,493
  • 3
  • 19
  • 42
  • The second way is like doing *[[NSString alloc]initWithString: @"Here's a test string in testString!"]*, except that since the string is literal and known at compile time, some optimizations may be made and the retain count (under ARC you can see it with *CFGetRetainCount*) is undefined. So this makes you understand that in the first case the first message pair alloc+init is useless. More details here: http://stackoverflow.com/questions/10775956/authoritative-description-of-objectivec-string-literals – Ramy Al Zuhouri Jun 11 '13 at 22:06
  • 2
    Another victim of the rather awful tutsplus tutorial, it seems. – bbum Jun 11 '13 at 23:24
  • @bbum I am already fairly fluent in Obj-C, but not so much memory management so was just skim reading that to refresh my memory and it surprised me. What comprehensive online tutorial would you recommend instead? – Sam Heather Jun 12 '13 at 00:30
  • 1
    If you are fluent in Objective-C, then you know how broken that code is? `testString = [[NSString alloc] init];` followed by an assignment to `testString` is completely meaningless. As far as recommendations? I always start with Apple's documentation and examples and go from there. – bbum Jun 12 '13 at 03:32

2 Answers2

3

I realize this might not be what you're asking, but the second example is a bad practice. The compiler wants a string literal for NSLog. It's not required, but prevents a potential security problem (as per the warning). The first argument is interpreted with the printf formatter. If you do not use a string literal for your format (first argument) and the string is user-inputted that user could crash your application by passing invalid format data.

You can read about the vulnerability here: http://en.wikipedia.org/wiki/Format_string_attack

You can rewrite 'Code 2' to avoid this problem like this:

NSString *testString = @"Here's a test string in testString!";
NSLog(@"%@", testString);
Michael Lawrie
  • 1,534
  • 11
  • 20
3

Code 1:

You're creating and then throwing away an empty NSString. Then using a format string to log a string literal.

Code 2:

You're directly trying to log a string literal (via a variable).

Your ideal code is a combination of both where you don't create the unused string and you use a format string while logging.

Wain
  • 118,658
  • 15
  • 128
  • 151