thisisdee
thisisdee

Reputation: 878

Objective-C: Question about NSString and scope

I have a global NSString variable that I declared in my ViewController.m file, outside of any methods, but not in my .h file.

NSString *menuString;

It is initialized inside webViewDidFinishLoad and it works when I do this

NSString *menu = [self getParameter:url :@"Menu"];
menuString = [menu copy];

but not when I do this

NSString *menu = [self getParameter:url :@"Menu"];
menuString = menu;

or

menuString = [self getParameter:url :@"Menu"];

Here, by "it works" I mean the value is saved and I can use it in other methods. Otherwise, during debug, it says that menuString is out of scope. I was wondering why it behaves differently depending on the initialization.

(getParameter is just a method that takes two strings and returns a string).

Thanks!

Upvotes: 1

Views: 224

Answers (2)

MarkPowell
MarkPowell

Reputation: 16540

[self getParameter:url :@"Menu"]; returns an autoreleased string object. This means during the next cycle of the Autorelease Pool it will be released. If nothing else has increased its retain count (retain or copy call), it will be dealloc'd. Once it's dealloc'd and you attempt to use it you will crash.

Your first example, you copy the string you now have an object that will not be cleaned up when the Autorelease Pool cleans up.

However, make sure you release the object in your class's dealloc method to prevent an leaks.

Upvotes: 1

filipe
filipe

Reputation: 3380

The method getParameter: returns an autoreleased NSString object.

That means that this object will be automatically released at the end of that run loop (when the autorelease pool is drained).

Because you never retained that object, once it's autoreleased it's dealloced and you can't use it anymore.

By doing a copy, you are creating a retained copy of that object that won't be autoreleased at the end of the run loop.
It would also work if you used retain:

menuString = [[self getParameter:url :@"Menu"] retain];

note that if you copy or retain it, you have to release it later at some point when you don't need it anymore, otherwise you'll have a memory leak.

Upvotes: 1

Related Questions