0

我已经搜索并尝试了很多,但在我的应用程序(使用 iOS 5 sdk)中,只有当我在 viewDidLoad 方法或任何按钮的单击事件中初始化并启动连接时,才会调用 NSURLConnection 委托方法。

但我想在解析我的 JSON 文件后调用它。并为 JSON 中的每条记录创建一个新连接。

谁能告诉我发生了什么?ios sdk 5 有什么变化吗?

这是我的代码:

-(void)getData:(NSString*)URL{
NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:URL]];

shortURL = [NSString stringWithString:URL];


connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];

//NSAssert(connection!=nil, @"no connection", nil);
[connection start];

}

- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response

{ // application specific stuff }

getData 函数是在继承自 NSObject 的类中编写的。它被称为

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

UITableView 的方法。

请帮我解决一下这个。

4

1 回答 1

2

假设 JSON 解析代码发生在后台线程中,您必须为该线程创建一个 NSRunLoop。

NSURLConnection 类只是将自身添加到运行循环中,如果不存在,则不会调用任何处理或委托方法。

connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
[[NSRunLoop currentRunLoop] run];

注意:run方法会阻塞

于 2012-02-10T18:04:06.163 回答