管理多个异步 NSURLConnection 连接 [英] Managing multiple asynchronous NSURLConnection connections
问题描述
我的班级中有大量重复代码,如下所示:
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.
推荐答案
我跟踪 CFMutableDictionaryRef 中的响应,该 CFMutableDictionaryRef 由与其关联的 NSURLConnection 键控.即:
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"]);
现在我有每个连接的信息"数据字典,我可以用它来跟踪有关连接的信息,信息"字典已经包含一个可变数据对象,我可以用它来存储回复数据进来了.
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 连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!