你可以做的是有一个自定义连接类来表示一个连接、它的数据,以及一些关于连接的可选信息。我用这个:
@interface MyConnection : NSObject
@property NSURLConnection *connection;
@property id info;
@property NSMutableData *data;
@end
然后只需将连接放在一个数组中,并将实际的 NSURLConnection 对象相互比较,以找出哪个连接接收到数据/失败等。
创建连接:
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:someRequest delegate:self];
if (connection){
MyConnection *con = [[MyConnection alloc] init];
con.connection = connection;
con.data = [NSMutableData data];
[self.arrayWithConnections addObject:con];
}
方法:
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
MyConnection *con = [self getConnection:connection]
[con.data appendData:data];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
MyConnection *con = [self getConnection:connection];
[con.data setLength:0];
}
-(MyConnection *)getConnection:(NSURLConnection *)con
{
for (MyConnection *myCon in self.arrayWithConnections)
if ([con isEqual: myCon.connection])
return myCon;
return nil;
}