views:

815

answers:

5

If I have an NSMutableString such as

NSMutableString *foo = [[NSMutableString alloc] init];

if I nil out the object, foo = nil, does that lower the retain count by 1, thus effectively releasing the memory? Would I need to reallocate foo from the heap at this point to be able to use it?

+2  A: 
does that lower the retain count by 1, thus effectively releasing the memory?

No

You should use

[foo release]
Igor
A: 

foo = nil; will not lower the retain count of the object. It will just make foo point nowhere instead of at the object. To decrement the retain count, you will have to say [foo release];.

Will Harris
+8  A: 

Please read the basic documentation. Setting a variable foo to nil does nothing to its previous content. Remember, foo is just a pointer to an object; to use it, you have to make it point to a valid object. Just to make it not point to that object any more doesn't release the object.

Jim Puls
+5  A: 

Assigning nil to a variable does not affect the value that was previously there. Retain counts are only lowered by release.

You should read Apple's Cocoa memory management guidelines. Cocoa's reference-counting system isn't that difficult, but it is something you have to learn, and if you don't learn it correctly, your program will have lots of subtle bugs that will drive you crazy.

Chuck
+4  A: 

What everybody said above is absolutely true. You need a release in that code snippet.

However, it's important to keep in mind that assigning to a property will lower the retain count if that's the right thing to do. That is:

foo = nil;         // doesn't lower
bar.foo = nil;     // probably does

Properties look like ordinary variables, but they really aren't; they handle their own memory management intelligently. That's something to keep in mind when you're working with them.

Brent Royal-Gordon
“Properties … handle their own memory management intelligently.” Assuming you declare them correctly, of course. If you declare it with @property(assign), it won't release.
Peter Hosey
This is true, but the assumption is that if you declare a property with (assign), it really shouldn't be retained (because it's a delegate, for example). In general, you should assume that another class's properties manage their values' memory correctly.
Brent Royal-Gordon