What does the following line actually do?
string = @"Some text";
Assuming that "string" is declared thusly in the header:
NSString *string;
What does the "=" actually do here? What does it do to "string"'s reference count? In particular, assuming that for some reason "string" is not otherwise assigned to, does it need to be released?
Thanks!
string
is not a string.string
is, in fact, not any other kind of Cocoa object, either.string
is a variable, which you've created to hold an instance of NSString. The assignment operator puts something into a variable*. In your example above, you create a literal string, and put that into the variable.Since
string
is a variable, not a Cocoa object, it has no reference count.Assigning an object somewhere can extend the object's lifetime in garbage-collected code (only on the Mac). See the Memory Management Programming Guide for Cocoa for more details.
*Or a C array. Don't confuse these with Cocoa arrays; they're not interchangeable, and you can't use the assignment operator to put things into a Cocoa collection (not in Objective-C, anyway).
When you use a literal like in this case, it is just syntactic sugar to quickly create an NSString object. Once created, the object behaves just like another other. The difference here is that your string is compiled into the program instead of created dynamically.
The assignment is just that. The
string
pointer is basically a label that points to specific address in memory. Reassignment statement would point that label to another address in memory!It doesn't change reference counting or do anything beyond that in Objective-C. You need to maintain the reference count yourself, if you are running in a non-garbage-collection environment:
However, string literals don't need to be managed, as they get allocated statically and never get deallocated! So the
release
andretain
methods are just NOOPs (i.e. no operations). You can safely omit them.