使用网络服务C#,我想显示有关产品的信息。为了加载数据,我使用dispatch_async作为队列执行,如下所示:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//Show loading
[ShareAppDelegate showloading];
//LOAD PRODUCT INFO
productDatasources = [self loadProductInfo];
//LOAD COMMENT
commentDatasources = [self loadComment];
//LOAD PRODUCT PHOTOS
photoDatasources = [self loadPhotos];
dispatch_async(dispatch_get_main_queue(), ^{
[ShareAppDelegate hideloading];
//UPDATE PRODUCT INFO TO UI
[self showProductInfoWithDatasource:productDatasources];
//UPDATE COMMENT INFO TO UI
[self showCommentWithDatasource:commentDatasources];
//UPDATE PHOTO INFO TO UI
[self showProductPhotoWithDatasource:photoDatasources];
});
});
但有时它工作正常,我的意思是,我的产品信息、评论和照片可以加载并显示在我的屏幕上。但有时,只能加载ProductInfo,Comment和Photos无法加载并获取null。有时,3 为空。
我发现,在我测试过的所有情况下,服务器总是正确返回结果,结果不为空。但我的dispatch_get_main_queue似乎是在数据完全接收之前执行的。
有人知道我的情况吗? dispatch_async 是否合适。提前致谢。
编辑:
我已经找到解决这个问题的方法了。由于在另一个 View 中,我声明并启动了 NSTimer 来调用另一个 Web 服务。该网络服务每 5 秒运行一次,以通知用户是否有来自服务器的任何通知。
timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(loadNotification:) userInfo:nil repeats:YES];
所以,在这种情况下,有时我调用了2个Web服务并同时接收数据,这就是GCD无法正确接收数据的原因。我可以更新通知并仍然正确执行上述 GCD 吗??
最佳答案
您在后台线程中分配的属性(productDataSources、commentDataSources、photoDataSources),它们是如何声明的?是否可以在其他地方访问它们?在这种情况下,可能是出了问题。
主线程使用的属性绝不能被后台线程更改,这就是我怀疑这里发生的情况。相反,在后台线程上使用临时变量,然后在返回主线程时更改实际变量,如下所示:
//Show loading on main thread (important)
[ShareAppDelegate showloading];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//LOAD PRODUCT INFO
NSArray *tempProductDatasources = [self loadProductInfo];
//LOAD COMMENT
NSArray *tempCommentDatasources = [self loadComment];
//LOAD PRODUCT PHOTOS
NSArray *tempPhotoDatasources = [self loadPhotos];
dispatch_async(dispatch_get_main_queue(), ^{
// Set the temp variables when on the main thread
productDatasources = tempProductDatasources;
// ... etc
[ShareAppDelegate hideloading];
//UPDATE PRODUCT INFO TO UI
[self showProductInfoWithDatasource:productDatasources];
//UPDATE COMMENT INFO TO UI
[self showCommentWithDatasource:commentDatasources];
//UPDATE PHOTO INFO TO UI
[self showProductPhotoWithDatasource:photoDatasources];
});
});
关于objective-c - 我的dispatch_async加载大量数据有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20539106/