String or nsstring with string

Suppose myProp is @property (save) NSString * myProp and is synthesized for us ....

self.myProp = @"some value";//string literal? self.myProp = [NSString stringWithString:@"some value"]; 

Is there any difference here? Is it the first string literal that doesn't get autoreleased, or is it just in memory for the current scope, and I don't need to worry about that?

+4
source share
3 answers

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

Such an object is created during compilation of time and exists throughout your execution of programs. The compiler makes such object constants unique on each module, and theyre never released, although you can save and release them like you do other objects.

+4
source

A string literal is a hard-coded NSString that exists indefinitely while your application is running. You can even send messages that are answered by NSString, for example [@"test" length] .

To answer your question, the first line sets the property to a string literal, and the second through an additional step of creating a new string based on the string literal.

+1
source

To add to the messages of Joshua and Preston, actually [NSString stringWithString:xxx] returns xxx itself when xxx is a literal. This is an implementation detail, so you should not write any program relying on this fact, but it is interesting to know.

You can verify this fact in this way:

  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 box 10.6.3, both pointers have the same address as the NSCFString class.

Remember: retain and release are your responsibility for the property, and they do not always decrease / increase the number of deductions. An implementation can perform any optimization if this optimization does not violate the ownership policy.

Or, in other words: write retain and release so that the objects are saved / destroyed when the implementation always makes a naive increase / decrease in the number of deductions. This is a contract between Cocoa and you. But Cocoa can and does do a lot of optimization.

+1
source

Source: https://habr.com/ru/post/1306270/


All Articles