Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS memory management: to release a string or not?

I know that the following does not need manual release (as its autoreleased):

NSString* str1 = [NSString string];

And this will need manual release:

NSString* str2 = [[NSString alloc] init];
[string2 release];

But how about this? It is autoreleased or not?

NSString* str3 = @"Example string";

And finally, looking at the snippet below: If I've understood iOS memory management correctly, then releasing RootViewController reference 'rvc' would clear the object so it wouldn't be usable it else where in the code - and I wouldn't want that. But then, should I at least set the reference to null? Or can I just leave thease references in the code without them causing memory leaks in the long run?

- (void)myMethod
{
RootViewController *rvc = (RootViewController *)navigationController.topViewController;
// using rvc somehow...
// ...but should I set it to null?
}
like image 895
Pompair Avatar asked Dec 18 '25 17:12

Pompair


2 Answers

No need to release the string literal — it's not autoreleased but it's also not created at that line. String literals are a special case (being the only sort of literal object in Objective-C) and they ignore any attempt to release them.

rvc is a local variable, so will become inaccessible as soon as MyMethod ends. There's no need to set it to anything (and it'd be nil, not null). The assignment you have doesn't do anything except get the address of the topViewController and store it in a local variable. So there's no memory management effect.

like image 78
Tommy Avatar answered Dec 21 '25 09:12

Tommy


If you use one of the words "Retain", "Alloc", "New", "Copy" (RANC) then you are the owner of the object and are responsible for memory management. You did not use one of the RANC words, therefore you do not need to release. See http://www.mobiledev.nl/memory-management-in-ios/ for a bit more explanation on this.

like image 26
Mobiledev.nl Avatar answered Dec 21 '25 09:12

Mobiledev.nl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!