ios - 执行网络异步请求的自定义类的内存管理

标签 ios memory-management asynchronous automatic-ref-counting nsurlconnection

我已经实现了一个类,其中我使用 NSURLConnection 及其委托(delegate)方法封装了一个异步请求。每当点击其 View 的按钮时,我都会在 View Controller 中创建此类的实例,并要求它发出网络请求:

- (IBAction)getData:(id)sender
{
   // Perform network request
   Updater *updater = [[Updater alloc] init];
   [updater queryService:self.date];
}

这样的queryService:方法是这样的:

- (void)queryService:(NSDate *)date
{
   self.responseData = [NSMutableData data];

   NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:kTimeout];
   NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
}

由于 Updater 正在执行异步操作,我不确定我已声明为局部变量的 updater 实例是否会保留到 connection:didFailWithError:connectionDidFinishLoading: 被调用,或者我会在调用中为 Updater 创建一个 strong 属性 View Controller 。我正在使用 ARC。

谢谢!

最佳答案

是的,会一直保留到连接结束(fail, success ecc)。 这是因为您的 Updater 实例是 NSURLConnection 的委托(delegate)。

NSURLConnection 文档中,您可以阅读:

Note: During a download the connection maintains a strong reference to the delegate. It releases that strong reference when the connection finishes loading, fails, or is canceled.

关于ios - 执行网络异步请求的自定义类的内存管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17642583/

相关文章:

Python 相当于 Java 的 `tryLock`(惯用语)?

ios - 架构 arm64 : "_FIRAuthStateDidChangeInternalNotificationAppKey", 的 undefined symbol 引用自

c# - 查找系统和程序内存使用情况的替代方法

ios - 有什么可以阻止 -[NSData bytes] 成为悬空指针吗?

node.js - 异步移动 Node 中的文件数组

javascript - Node.js:如何以编程方式确定异步?

iphone - 无法设置 CCLabelTTF anchor

ios - Swift:UIWebView 加载旧内容

ios - 新模型的架构版本更新

c++ - 关于 C++/程序集数据布局、数据成员访问、方法的一般问题