开发者

NSURLConnection Leaks -- Why?

开发者 https://www.devze.com 2022-12-11 01:07 出处:网络
NSURLConnection *connection is a property of the class @property (nonatomic, retain) NSURLConnection *connection;

NSURLConnection *connection is a property of the class

@property (nonatomic, retain) NSURLConnection *connection;

Instruments is reporting that I'm leaking an NSURLConnection object in the second line of the code below.

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:_url];
self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[request release];

In the didFinishLoading and didFinishWithError delegate selectors, I'm releasing the connection and开发者_如何学C setting to nil

[self.connection release];
self.connection = nil;

I've read the "NSURLConnection leak?" post and several others. I feel like I must be missing something totally obvious. Help?


As the comment from roe said, you are allocating the connection (retain count 1) and then retaining it again with your connection property (retain count 2). You only release once in the delegate selectors. You have two options:

1) Change your connection property to assign rather than retain.

@property (nonatomic, assign) NSURLConnection *connection;

// OR, since assign is the default you may omit it

@property (nonatomic) NSURLConnection *connection;

2) Release the allocated object after it is retained by your connection property:

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:_url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
self.connection = connection;
[connection release];
[request release];

Option 2 is preferred since there is less of a chance for leaks since alloc and release are as close together as possible. Also, if you forget to release the previous connection the synthesized methods will release the previous one for you. Don't forget to release self.connection in dealloc.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号