调用reloadData时,UICollectionView不会立即更新,而是在30-60秒后随机更新

正如标题所暗示的,我的UICollectionView不会在调用reloadData之后立即更新和显示单元格。 相反,它似乎最终在30-60秒后更新我的collections视图。 我的设置如下:

UICollectionView添加到视图控制器在故事板与delegatedataSource设置为视图控制器和标准sockets设置numberOfSectionsInRowcellForItemAtIndexPath都实现了并引用原型单元格和cellForItemAtIndexPath里面

这里是转到Twitter的代码,得到一个时间表,把它分配给一个variables,重新加载一个表视图与推文,然后通过推文find照片,并重新加载收集视图与这些项目。

即使我注释掉代码来显示图像,它仍然不会改变任何东西。

 SLRequest *timelineRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:timelineURL parameters:timelineParams]; [timelineRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) { if(responseData) { JSONDecoder *decoder = [[JSONDecoder alloc] init]; NSArray *timeline = [decoder objectWithData:responseData]; [self setTwitterTableData:timeline]; for(NSDictionary *tweet in [self twitterTableData]) { if(![tweet valueForKeyPath:@"entities.media"]) { continue; } for(NSDictionary *photo in [[tweet objectForKey:@"entities"] objectForKey:@"media"]) { [[self photoStreamArray] addObject:[NSDictionary dictionaryWithObjectsAndKeys: [photo objectForKey:@"media_url"], @"url", [NSValue valueWithCGSize:CGSizeMake([[photo valueForKeyPath:@"sizes.large.w"] floatValue], [[photo valueForKeyPath:@"sizes.large.h"] floatValue])], @"size" , nil]]; } } [[self photoStreamCollectionView] reloadData]; } }]; 

这是从后台线程调用UIKit方法的典型症状。 如果您查看-[SLRequest performRequestWithHandler:]文档 ,则说明处理程序不保证将在哪个线程上运行。

将你的调用包装在reloadData中并传递给dispatch_async() ; 也传递dispatch_get_main_queue()作为队列参数。

您需要将更新发送到主线程:

  dispatch_async(dispatch_get_main_queue(), ^{ [self.photoStreamCollectionView reloadData]; }); 

或在Swift中:

 dispatch_async(dispatch_get_main_queue(), { self.photoStreamCollectionView.reloadData() }) 

苹果说:你不应该在插入或删除项目的animation块的中间调用这个方法。 插入和删除操作会自动使表的数据得到适当的更新。

在脸上:你不应该在任何animation的中间调用这个方法(包括在滚动UICollectionView)。

所以你可以:

 [self.collectionView setContentOffset:CGPointZero animated:NO]; [self.collectionView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO]; 

或者确定没有任何animation,然后调用reloadData; 要么

 [self.collectionView performBatchUpdates:^{ //insert, delete, reload, or move operations } completion:nil];