Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does assigning a literal string to an NSString with "=" actually do?

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!

like image 819
notMyScreenName Avatar asked Jan 13 '10 04:01

notMyScreenName


2 Answers

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:

[string release];
string = [@"Some text" retain];

However, string literals don't need to be managed, as they get allocated statically and never get deallocated! So the release and retain methods are just NOOPs (i.e. no operations). You can safely omit them.

like image 137
notnoop Avatar answered Nov 16 '22 03:11

notnoop


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?

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).

like image 20
Peter Hosey Avatar answered Nov 16 '22 03:11

Peter Hosey