Sam Heather
Sam Heather

Reputation: 1503

NSString Class - Sample Code Online

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

Upvotes: 0

Views: 1711

Answers (2)

Michael Lawrie
Michael Lawrie

Reputation: 1554

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);

Upvotes: 3

Wain
Wain

Reputation: 119031

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.

Upvotes: 3

Related Questions