如果我理解正确,您只需在 viewDidUnload 或 dealloc 方法中执行 [whateverConnection cancel] 即可。这将取消连接。如果你有一个自定义的下载器对象,例如一些使用 NSURLConnection 的大图像,这几乎是一样的。为您的类创建一个取消方法(取消连接并释放它)并在控制器的 dealloc 方法中调用它。您还应该使用类似 wasCanceled 的 bool 标志,并且如果从您的取消方法中设置了 wasCanceled,则不要从您的自定义对象的委托中调用任何方法。(您只有一个指向您的委托的弱指针,因此当其他对象调用您的取消方法时,它可能已经被释放)。我假设您的自定义对象的委托是视图控制器。我有几个这样的下载器,它工作正常,
@interface CompaniesDownloader : NSObject /*<NSXMLParserDelegate>*/
{
id<CompaniesDownloaderDelegate> delegate; //a view controller is the delegate
NSMutableArray *companies;
BOOL isWorking;
BOOL wasCanceled;
@private
//url connection object
NSURLConnection *companiesConnection;
//this is where i put the binary data that gets transformed into xml
NSMutableData *webData;
//temporary string used when parsing xml
NSMutableString *tmpString;
//temporary company used when parsing xml
Company *tmpCompany;
}
在实施中:
-(void) cancel
{
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible: FALSE];
wasCanceled = TRUE;
[companiesConnection cancel];
[webData release];
webData = nil;
self.companiesConnection = nil; //OR [companiesConnection release]; companiesConnection=nil;
isWorking = FALSE;
}