管理多个异步NSURLConnection连接

管理多个异步NSURLConnection连接

本文介绍了管理多个异步NSURLConnection连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在类中有很多重复的代码,如下所示:

I have a ton of repeating code in my class that looks like the following:

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
                                                              delegate:self];

异步请求的问题是当您有各种请求关闭时,将它们全部作为一个实体,大量的分支和丑陋的代码开始制定开始:

The problem with asynchronous requests is when you have various requests going off, and you have a delegate assigned to treat them all as one entity, a lot of branching and ugly code begins to formulate going:

我们得到什么样的数据?如果它包含这,做那,否则做其他。这将是有用的,我认为能够标记这些异步请求,有点像你能够标记视图与ID。

What kind of data are we getting back? If it contains this, do that, else do other. It would be useful I think to be able to tag these asynchronous requests, kind of like you're able to tag views with IDs.

我很好奇什么策略对于管理处理多个异步请求的类最有效。

I was curious what strategy is most efficient for managing a class that handles multiple asynchronous requests.

推荐答案

我跟踪由与其关联的NSURLConnection键入的CFMutableDictionaryRef中的响应。即:

I track responses in an CFMutableDictionaryRef keyed by the NSURLConnection associated with it. i.e.:

connectionToInfoMapping =
    CFDictionaryCreateMutable(
        kCFAllocatorDefault,
        0,
        &kCFTypeDictionaryKeyCallBacks,
        &kCFTypeDictionaryValueCallBacks);

这可能看起来奇怪,而不是NSMutableDictionary,但我这样做,因为这个CFDictionary只保留其键(NSURLConnection),而NSDictionary复制其键(而NSURLConnection不支持复制)。

It may seem odd to use this instead of NSMutableDictionary but I do it because this CFDictionary only retains its keys (the NSURLConnection) whereas NSDictionary copies its keys (and NSURLConnection doesn't support copying).

完成后:

CFDictionaryAddValue(
    connectionToInfoMapping,
    connection,
    [NSMutableDictionary
        dictionaryWithObject:[NSMutableData data]
        forKey:@"receivedData"]);

现在我有一个用于每个连接的数据的info字典,关于连接,并且info字典已经包含了一个可变的数据对象,我可以使用它来存储回复数据。

and now I have an "info" dictionary of data for each connection that I can use to track information about the connection and the "info" dictionary already contains a mutable data object that I can use to store the reply data as it comes in.

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSMutableDictionary *connectionInfo =
        CFDictionaryGetValue(connectionToInfoMapping, connection);
    [[connectionInfo objectForKey:@"receivedData"] appendData:data];
}

这篇关于管理多个异步NSURLConnection连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 23:19