<分区>
<分区>
我一直用于连接服务器单例类。我没有检查服务器的响应并轻松获取数据。现在我需要使用 10 个不同的请求。我创建属性 NSURLConnection。那么我如何识别我在委托(delegate)方法中使用的连接,例如
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
因为我从每个请求中获取不同的数据
最佳答案
您可以做的是拥有一个自定义连接类来表示一个连接、它的数据以及可选的一些关于该连接的信息。我用这个:
@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;
}
关于ios - 不同 NSURLConnection 的单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16010532/
相关文章:
ios - UIVIew 大小在界面生成器中使用设备大小并且没有限制
ios - 在 iOS 中检索 HTTPResponse/HTTPRequest 状态代码?
swift - iPhone 中 https 连接中连接失败或无响应之间的区别
iphone - 更改部分的 uiTableview 单元格样式
ios - 在 Swift 中,为什么 "let _ = this"比 "this != nil"快?
ios - 从 1.1 升级到 1.2 后出现奇怪的快速错误
objective-c - 在 iOS 5 中关闭多个 View Controller
iphone - 在 NSURLConnection 下载期间更新 iPhone UIProgressView
objective-c - Cocoa Touch 相当于 JavaScript 的焦点/模糊
ios - 无法使用 ARC 设置自定义协议(protocol)委托(delegate),并使用 UINavigationController 和两个 UITableViewController