iOS ARC Fire and Forget ASYNC 包装器的最佳实践

iOS ARC Best Practices for Fire and Forget ASYNC Wrappers

我有一个相当简单的 NSURLConnectionDelegate 包装器 class 可以为我的应用程序处理简单的 HTTP 请求。

当这些请求 return 时,它们会调用我的主视图控制器中的后续委托方法 class 以通知我结果是否成功。

如果我采取一劳永逸的方法在我的视图控制器中的方法中使用这些包装器,如下所示:

- (void) Foo {
    MySimpleRequest* request = [[MySimpleRequest alloc] initWithDelegate:self];
    [request send];
}

一旦 Foo 退出,request 似乎就被 ARC 清除了,后续的委托方法也不会被调用。

如果我将我的 request 指针移动到 class 级别,它会停留并成功。

这是推荐的方法吗?我是否必须让成员变量保留每个请求,或者有没有办法在请求 returns 之前保持其生命周期?

我希望始终保留对请求的 'external' 引用。如果你不想要这个,我想你可以在 MySimpleRequest class.

中创建对 self 的强引用

确保将它设置为 nil,否则你会明显地发生内存泄漏。

您可以使用块来 return 下载数据,并让下载器 class 成为下载的委托,这样所有委托方法都可以包含在 class.我使用 class 来处理 NSURLConnection,并从 didFailWithError 或 connectionDidFinishLoading: 调用完成块。下载程序 class 在块执行后被释放。我这样从视图控制器调用它,

    Downloader *dl = [Downloader new];
    NSURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.wswd.net/testdownloadfiles/20MB.zip"]] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10];

    [dl downloadWithRequest:request completion:^(NSData *data, NSError *error) {
        if (data) {
            // do whatever you need to do with the raw data here
            NSLog(@"got the data");
        }else{
            NSLog(@"%@",error);
        }
    }];