Reputation: 7721
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?
Upvotes: 4
Views: 3049
Reputation: 34185
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.
Upvotes: 1
Reputation:
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.
Upvotes: 1
Reputation: 61228
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.
Upvotes: 4