检查哪个请求来自NSURLConnection委托

什么是检查哪个请求是委托方法内的哪个最好的方法:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { } 

现在我有一个NSURLConnection,我做了一个NSURLConnection请求之前,并在didReceiveResponse我做的:

 if (self.tempConnection == connection) 

但是有一个可能性,这不适用于比赛条件。 有一个更好的方法吗?

在OS5中有一个更好的方法。 忘记所有那些烦人的代表信息。 让连接为您build立数据,并将您的完成代码与您的开始代码一致:

 NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.site.com"]]; NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response; NSLog(@"got response %d, data = %@, error = %@", [httpResponse statusCode], data, error); }]; 

我已经看了很多不同的方式来做到这一点,而且我发现到目前为止,pipe理最干净和最简单的就是使用块模式。 这样,您可以保证在完成时响应正确的请求,避免竞争状况,并且在asynchronous调用期间您没有任何variables或对象超出范围的问题。 阅读/维护代码也容易得多。

ASIHTTPRequest和AFNetworking API都提供了一个块模式(不过ASI不再支持,所以最好用AFNetworking来处理新的东西)。 如果您不想使用这些库中的一个,但想自己做,可以下载AFNetworking的源代码并查看它们的实现。 但是,这似乎是很多额外的工作,没有什么价值。

考虑创build一个单独的类来充当代表。 然后,对于每个生成的NSURLConnection,实例化一个委托类的新实例,以用于该NSURLConnection

下面是一些简短的代码来说明这一点:

 @interface ConnectionDelegate : NSObject <NSURLConnectionDelegate> 

…然后在.m文件中实现这些方法

现在,我猜你可能有你在UIViewController子类(或其他类服务于不同的目的)张贴的代码?

无论你在哪里开始请求,使用这个代码:

 ConnectionDelegate *newDelegate = [[ConnectionDelegate alloc] init]; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"<url here">]]; [NSURLConnection connectionWithRequest:request delegate:newDelegate]; //then you can repeat this for every new request you need to make //and a different delegate will handle this newDelegate = [[ConnectionDelegate alloc] init]; request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"<url here">]]; [NSURLConnection connectionWithRequest:request delegate:newDelegate]; // ...continue as many times as you'd like newDelegate = [[ConnectionDelegate alloc] init]; request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"<url here">]]; [NSURLConnection connectionWithRequest:request delegate:newDelegate]; 

您可能会考虑将所有委托对象存储在NSDictionary或其他数据结构中以跟踪它们。 我会考虑在connectionDidFinishLoading中使用NSNotification来发布连接已完成的通知,并为从响应创build的任何对象提供服务。 让我知道你是否想要代码来帮助你形象化。 希望这可以帮助!