Still a little confused about Objective-C memory management. I think my confusion stems from what exactly the autorelease means.
NSString *theBackendResponse = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];
NSDictionary *accountDictionary = [theBackendResponse propertyList];
[viewController setAccountDictionary:accountDictionary];
Now, what should I do with the accountDictionary in the setAccountDictionary method of my view controller? Right now I just set the instance variable “accountDictionary” to whatever is returned. Should I set it to a retained one, and then release the one that’s returned? What should my setter code block look like, given that NSString’s propertyList method is autoreleased?
By the way, if I release theBackendResponse, will I lose the accountDictionary? I assume not…
Calling
[objectInstance autorelease]adds an object to the currentNSAutoreleasePool. When that pool receives adrainmessage, it sends areleaseto all the objects in the pool. If any of those objects’ retainCount reaches 0, they are deallocated at that point. The purpose of autorelease is to allow you to mark an object to be released “some time in the future”. This is especially useful for things like methods that return a newly allocated object but want to release it so that the caller doesn’t have to take ownership of the returned object. A method might look like this:The caller of
myMethodwould thenretainthe return value if they wanted to take ownership of the returned value or ignore it if not. When the currentNSAutoreleasePoolis drained,myObjwill get a release message. If no other objects own it (i.e. have sent it aretainmessage), it will get deallocated.All of this is explained in the Cocoa Memory Management Programming Guide. Even if you’ve already read it, it’s always worth an other read.
So, to answer your questions:
First, you should release
theBackendResponse. You will leak memory if you do not. You don’t need to know whataccountDictionarydoes with the string: if it needs to keep a reference it will have retainedtheBackendResponse. You have an ownership oftheBackendResponsebecause youalloc‘d it, so you must relinquish that ownership (viareleaseor indirectly viaautorelease).Second, you must retain or copy the argument to
setAccountDictionary:if you want to keep a reference to that object or value respectively. The standard setter method looks something like this (assuming you do not need atomic semantics):You must also remember to
releaseaccountDictionary in the dealloc method:Since you appear to be using
NSViewController, I assume you’re on Leopard (OS X 10.5) in which case, you should probably be using@propertyand the@synthesized getter/setter if possible. To do this, add adeclaration to the class
@interface. And add a@synthesize accountDictionary;directive in the@implementationblock for your controller class.