Reputation: 11865
What is difference between this two lines, they are in different apps but first one seems to work and I have problems with the second one; and which one should i choose over another? my app will constantly receive and send back data with a webservice.
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:request delegate:self];
And where should I release the connection object, after every didFinishLoading? but then doesn't it take much time on every request to connect?
Upvotes: 0
Views: 152
Reputation:
with first line you create an object with init method , which make you the owner of the object , so you must release it . The second line you use a convenient constructor, which does not make you owner of that object.in this case, if you want to manipulate with life-cycle of that object you must send another message to retain it : NSURLConnection *theConnection = [[NSURLConnection connectionWithRequest:request delegate:self] retain], and the count of object will be 2 .. even if in the second line your object automatically receive a autorelease message , the count after that will be 1 .. so if you retain object you must release it ...
you asked : And where should I release the connection object ? i think in method called connectionDidFinishLoading:connection or in the method connection:didFailWithError:
Upvotes: 2
Reputation: 26400
The first one is an instance of NSURLConnection
where you take ownership of the object, so you have the responsibility and hence must release it. Details on ownership reference.
The second one is an auto-released object so you dont need to release it. It will be released automatically when the auto-release pool is drained.
Upvotes: 2
Reputation: 15813
The second creates an auto-released connection, so if you don't explicitly retain it, it will disappear and your application will probably crash.
You can use either, you just need to understand objective-c memory management on the iPhone.
There is, as ever, a good explanation on the Apple site, it really is worth reading and understanding as once the penny drops, you'll never make the same mistake again.
Upvotes: 2