string or nsstring with string

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?

Answers


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.


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.


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.


Need Your Help

Batch file for copying files

command-line batch-file copy dos xcopy

I'm looking to do some massive copy's during a server migration and I need to better understand the copy commands in Windows Server. I've been toying with xcopy, but I really am having a difficult ...