views:

278

answers:

4

Greetings,

I'm sure that this is probably an incredibly stupid question, but...

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!

+3  A: 

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.

notnoop
Thanks! That's what I expected regarding the pointer assignment......Aah, so the "-1" retain count after the assignment ( i.e. [string retainCount]) is a flag indicating that "string" points to a string literal that thus doesn't need to be managed, but can be safely released?
notMyScreenName
A: 

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.

darren
+1  A: 

This post has a great explanation from Chris Hanson of how string literals and constant strings behave - and differ - in Objective-C.

rpj
A: 

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

Peter Hosey