考虑创建一个单独的类作为委托。然后,对于每个生成的 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 来发布连接完成的通知,并提供从响应创建的任何对象。让我知道您是否需要代码来帮助您将其可视化。希望这可以帮助!