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!
The method
getParameter:returns an autoreleasedNSStringobject.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:note that if you
copyorretainit, you have to release it later at some point when you don’t need it anymore, otherwise you’ll have a memory leak.