tags:

views:

680

answers:

3

Lets assume myProp is @property (retain) NSString * myProp and synthesized for us....

self.myProp = @"some value";//string literal?

self.myProp = [NSString stringWithString:@"some value"];

Is there a difference here? Is the first one a string literal that doesnt get autoreleased or is it just in memory for it's current scope and I dont have to worry about it?

+4  A: 

You might want to spend some time with the String Programming Guide. From the linked section (about creating @"string constants"):

Such an object is created at compile time and exists throughout your program’s execution. The compiler makes such object constants unique on a per-module basis, and they’re never deallocated, though you can retain and release them as you do any other object.

Joshua Nozzi
Thanks, thats what I was thinking. Looks like I will keep using my NSString object.
joels
+1  A: 

A string literal is a hard-coded NSString that exists indefinitely while your application is running. You can even send it messages that NSString responds to, such as [@"test" length].

To answer your question, the first line is setting the property to the string literal, while the second is going through an extra step of creating a new string based off the string literal.

Preston
+1  A: 

To add to the posts by Joshua and Preston, in fact [NSString stringWithString:xxx] returns xxx itself when xxx is a literal. This is an implementation detail, so you shouldn't write any program relying on this fact, but it's fun to know.

You can check this fact thus:

 NSString*a=@"foo";
 NSString*b=[NSString stringWithString:a];
 NSLog(@"a at %p, class %@",a,[a class]);
 NSLog(@"b at %p, class %@",b,[b class]);

At least on my 10.6.3 box, both give the same address, with class NSCFString.

Remember: retain & release concern your responsibility on the ownership, and they don't always decrease/increase the retain count. The implementation can do whatever optimization it wants, as long as the said optimization doesn't break the ownership policy.

Or in other words: write retain & release so that the objects are kept/destroyed in the case the implementation always does the naive increase/decrease of the retain count. That's the contract between Cocoa and you. But Cocoa can do and indeed does a lot of optimization.

Yuji