【发布时间】:2012-02-04 22:34:27
【问题描述】:
我正在使用NSURLConnection 类通过 Internet 获取一些数据,我的应用程序在某个时候崩溃了,我收到一个错误,表明我已经双重释放了一个对象,
以下是我如何创建NSURLConnection 的实例以及如何发布它:
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[connection release];
我应该在用完后释放它,对吗?还是在幕后发布?
编辑
现在我解决了这个问题,只是我将NSURLConnection的实例作为ivar并在dealloc中释放它,这是代码
头文件:
// ....
NSURLConnection *connection;
@property (nonatomic, retain) NSURLConnection *connection;
实现文件:
// ...
NSURLRequest *request = [NSURLRequest requestWithURL:url];
self.connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
// ...
-(void)dealloc{
[connection release];
[super dealloc];
}
问题是我在分配新连接之前没有释放旧连接,这是通过在 ivar 之前添加 self 来完成的。
【问题讨论】:
-
考虑在您的项目中使用 ARC,它将有助于解决这种情况。
-
我总是使用在 connectionDidFinish 加载或 connectionDidLoadWithError 中释放它(不确定确切的名称,但您必须有一个想法)...因为这两种方法都与您正在使用的当前连接有参数。 ..
-
如果我设法在 didFinishLoading 和 didFinishWithErro 中释放它,你的意思是不需要在 dealloc 方法中释放它?谢谢
标签: objective-c ios cocoa-touch