1

我有以下代码,它连接到服务器(实际上是我现在自己的机器),下载一些数据,将其反序列化,并将其分配给全局变量。

UINavigationController *navController = (UINavigationController *)self.window.rootViewController;
MasterViewController *masterController = [navController.viewControllers objectAtIndex:0]; // masterController is a UITableViewController subclass
NSMutableArray *surveys = [[NSMutableArray alloc] init];
NSURL *url = [NSURL URLWithString:@"http://127.0.0.1:8000/testapp/survey-data"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *rep, NSData *d, NSError *err) {
    if(d) {
        NSMutableArray *allSurveys = [NSJSONSerialization JSONObjectWithData:d options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        for(NSMutableArray *item in allSurveys) {
            NSString *title = [item objectAtIndex:[item count] - 1];
            [item removeLastObject];
            Survey *survey = [[Survey alloc] initWithArray:item title:title];
            [surveys addObject:survey];
        }
        masterController.surveys = surveys;


        NSLog(@"%@", [masterController.surveys description]);
    }
}];

不幸的是,它不起作用。(NSLog()在处理程序块内)按预期打印出所有数据。显然,连接正在工作。但是,视图不会更新,并且行都是空白的。发生这种情况是因为下载完成后块被调用吗?我怎样才能避免这种情况?

它似乎也可能是由于在块中设置变量引起的。不过,我查看了 Apple 的文档,看起来这应该不是问题,因为我通过对masterViewController. 我错了吗?

我应该注意,我尝试将其重写为使用 a [NSURLConnection sendSynchronousRequest:returningResponse:error:,效果很好。但是,如果网络速度慢或出现故障,同步请求可能是一个糟糕的主意,所以我真的需要让它异步工作。

4

2 回答 2

1

AsynchronousRequest不使用 UI 更新发生的主线程,所以对于 UI 更新使用这个:

dispatch_async(dispatch_get_main_queue(), ^{ 
    //UI update here    
});
于 2012-05-28T10:05:38.930 回答
1

由于您的视图在获取数据之前加载,因此您需要reloadData在数据到达后调用表视图。

为了防止其他问题,请确保您在主线程上执行此操作,因为 UIKit 类不是线程安全的。

于 2012-05-28T15:14:42.890 回答