views:

920

answers:

3

I'm really confused with NSStrings. Like when should I do

NSString *aString = @"Hello";

of should it be:

NSString *aString = [[NSString alloc] initWithString:@"Hello"];

But then its different when you're assigning a value to an NSString property isn't it? Can someone clear this up for me?

Thanks!!

A: 

This question has been asked multiple times:

http://stackoverflow.com/questions/329977/cocoa-memory-management-with-nsstring http://stackoverflow.com/questions/637022/do-nsstring-objects-need-to-be-alloc-and-init

Compiler allocated strings (of the format @"STRING") are constant, and so -retain, -release, and -autorelease messages to them are ignored. You don't have to release or autorelease foo in this case (but it won't hurt).

micmoo
A: 
NSString *aString = @"Hello";

Will create an autoreleased string. That is, if you don't explicitly retain it, it will might disappear after your method is over (and sometimes that's totally fine). But if you want to hold on to it past that time, you'll need to retain it.

If you create a property for that string like this

@property (retain) NSString *aString;

And then assign like this:

self.aString = @"Hello";

Then you've properly retained the string and it will stick around.

On the other hand, using alloc, init will create a string for you with a retain count of 1, and if you don't need it past that method, you should release it.

**Edit: @"Hello" is not an autoreleased string, as others have pointed out. My bad. **

jbrennan
This is incorrect. You do not need to retain a constant NSString. It is not created autoreleased, it is a special subclass of the NSString class cluster that does not allocate any memory because it is mapped into a read only page of the program.
Louis Gerbarg
Did you not see my edit?
jbrennan
+2  A: 

In general you should do the first, but they are mostly functionally the same. You can treat constant NSStrings just like normal NSString string objects, for instance:

[@"Hello" length]

will return 5. You can assign them to properties, everything just works. The one thing you might notice is that with the constant NSStrings you don't have to worry about retain/release. That is because they are actually mapped into the applications readonly data section, and don't have allocated memory. Retain and release calls against them still work, they just become noops.

Louis Gerbarg
Ok but say I wanted to format it I'll need to alloc initWithFormat (or the stringWithFormat autorelease method) right?
Mk12
Yeah, because a string you are generating via a format is not constant, it is dynamically created at runtime.
Louis Gerbarg