Completely new to Objective-C, trying to find out when I need to alloc and release objects.
For example, I want to fetch some data from the Web. I found an article at Apple which has this code:
NSURLRequest *theRequest=[NSURLRequest requestWithURL:
[NSURL URLWithString:@"http://www.apple.com/"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc]
initWithRequest:theRequest delegate:self];
What I don’t understand is: Why do they need to call alloc on the connection but not on the request? How do I know when I need alloc and when not?
Similar questions for release. From what I read, I only ever need to release objects that were initialized using alloc/init. But all “initWithXXX” functions return autoreleased objects instead.
Is this a hard rule, or just convention? Is there a way to find out if I need to release an object or not?
Please read the Memory Management Programming Guide. All of these are explained there. Also check out Learn Objective-C.
Whenever you need to own an object to make it live longer than the function’s scope, the object needs to be
-retained. Of course you could usebut the connection will be
-autoreleased. But because there’s time for a connection to finish, this variable should be-retained to prevent the connection becoming invalid. Of course, then, you could doBut this is equivalent to
+alloc→-init→-autorelease→-retain, the last two steps are redundant. Probably that’s why Apple chooses to use+alloc/-inithere.(BTW, this style would cause the static analyzer to complain. It’s better to store
theConnectionas an ivar somewhere, e.g. in the delegate object.)On the other hand, the NSURLRequest is just a temporary object, so it needs to be
-released when the function ends. Again, you could usethis is even more efficient, as the autorelease pool won’t be filled up, but using this method one may forget to
-releaseand cause a leak.No,
-init…should never return an-autoreleased object.