anon
anon

Reputation:

NSMutableString and nil for memory management

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?

Upvotes: 5

Views: 1810

Answers (5)

Becca Royal-Gordon
Becca Royal-Gordon

Reputation: 17861

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.

Upvotes: 4

Chuck
Chuck

Reputation: 237080

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.

Upvotes: 5

Jim Puls
Jim Puls

Reputation: 81092

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.

Upvotes: 8

Will Harris
Will Harris

Reputation: 21695

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];.

Upvotes: 0

Igor
Igor

Reputation: 1258

does that lower the retain count by 1, thus effectively releasing the memory?

No

You should use

[foo release]

Upvotes: 2

Related Questions