Pompair
Pompair

Reputation: 7321

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?
}

Upvotes: 2

Views: 3677

Answers (3)

Mobiledev.nl
Mobiledev.nl

Reputation: 51

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.

Upvotes: 5

Tommy
Tommy

Reputation: 100632

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.

Upvotes: 6

Andrew
Andrew

Reputation: 24846

@"Example string" is a compile time constant. The memory is allocated by compiler. So in the line

NSString *str3 = @"Example string";

you are just assigning to a constant and you should not release str3

Upvotes: 1

Related Questions