Objective-C autorelease pool
I am starting my Objective-C journey with "Cocoa Programming" by Daniel H Setinberg. There is a bit that got me surprised related to the memory management. Actually I do find memory management in Objective C more complicated than in C, though I have not touched a "non garbage collecte开发者_运维问答d language" for a while so the old times of using malloc and its friends may be idealized in my memory :).
The bit that confused me is the following:
-(void) loadURLFromTextField{
NSURL *url = [NSURL URLWithString:self.address.text];
NSURLRequest *request = [NSURLRequest requestWithUrl:url];
[self.webView loadRequest:request];
}
in second and third line I am allocating two objects so I assumed I need to release them somewhere. Yet the comment for this bit of code states:
"Note that we're using class methods to construct autoreleased instances of the request and the URL. We don't need to release them ourselves."
Could someone help me understand why those instances are autoreleased and how to get this from the SDK documentation. Is it a standard that all such class methods returining an object instance are actually autoreleased. Thanks for your help in advance!
You don't have to release them as you don't «own» them (you did not allocate them explicitly, nor retained them).
Auto-released objects are placed on the current instance of the NSAutoreleasePool class, that will automatically send them a release message the next time the pool is drained, so usually at the end of the current run loop.
That's called convenience methods, that returns auto-released objects.
So if you do not call alloc, or retain, you basically don't own the objects, so you should not care about releasing them, as someone else will do...
If you release them, the you'll probably have a segfault, as releasing twice an object may lead to a double free...
For instance:
NSArray * myArray = [ NSArray emptyArray ];
Auto-released object, by convenience method. You don't own it, so you don't have to release it.
NSArray * myArray = [ [ NSArray emptyArray ] retain ];
You'll have to release the array, as you retained it.
NSArray * myArray = [ [ NSArray alloc ] initWithArray: someArray ];
Same here, as you explicitly allocated the array.
NSArray * myArray = [ [ [ NSArray alloc ] initWithArray: someArray ] autorelease ];
No need to release here, as the object has been placed in the auto-release pool, and will receive a release message automatically.
In objective-c memory allocation is about ownership. In principle methods that contain the words new,alloc,copy or mutableCopy are presumed to return an object that you own and thus must release, all other methods return autoreleased objects for which you do not need to release however can take over ownership by doing a retain.
you can read more here
精彩评论