【问题标题】:NSURLConnection Delegate not workingNSURLConnection 委托不起作用
【发布时间】:2012-01-27 15:55:05
【问题描述】:

我已经搜索并尝试了很多,但在我的应用程序(使用 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 的方法。

请帮帮我。

【问题讨论】:

  • 最后一个委托方法在 iOS 5 中被贬低,请阅读文档
  • 请在此处提供代码块,以便识别实际问题。
  • 我正在使用“willReceiveResponsse”方法。我认为它没有被弃用。
  • JSON 解析代码可能在后台线程中吗?在这种情况下你需要手动启动一个运行循环

标签: iphone objective-c nsurlconnection ios5 nsurlconnectiondelegate


【解决方案1】:

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

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

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

注意:run方法会阻塞

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-11
    • 2011-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-29
    • 1970-01-01
    相关资源
    最近更新 更多