我在使用 NSFetchedResultsController 时遇到问题,我无法阻止它冻结 UI。初始提取发生得很快,但是当我触发任何错误时,它会在滚动表格视图时导致冻结。我只使用 8 个元素进行测试,我的后端使用 StackMob
这是我声明 NSFetchedResultsController 的地方
- (NSFetchedResultsController *)fetchedResultsController {
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Post"
inManagedObjectContext:_managedObjectContext];
[fetchRequest setEntity:entity];
NSSortDescriptor *sort = [[NSSortDescriptor alloc]
initWithKey:@"createddate" ascending:NO];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
NSFetchedResultsController *theFetchedResultsController =
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:_managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
_fetchedResultsController = theFetchedResultsController;
return _fetchedResultsController;
}
这是我的viewDidLoad:
- (void)viewDidLoad
{
[super viewDidLoad];
UIColor* backgroundImage = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:BACKGROUND_IMAGE_TAN]];
[[self view] setBackgroundColor:backgroundImage];
[[self tableView] setSeparatorStyle:UITableViewCellSeparatorStyleNone];
_managedObjectContext = [[self.appDelegate coreDataStore] contextForCurrentThread];
NSError *error;
if (![[self fetchedResultsController] performFetch:&error]) {
// Update to handle the error appropriately.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort(); // Fail
}
}
这是我的 cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"CCCell";
CCCell *cell = (CCCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CCCell" owner:nil options:nil];
cell = [topLevelObjects objectAtIndex:0];
[cell setDelegate:self];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
Post* post = (Post*)[_fetchedResultsController objectAtIndexPath:indexPath];
//
//IF I UNCOMMENT THIS LINE IT LOCKS THE UI
//
//NSLog(@"%@", [post valueForKey:@"price"]);
return cell;
}
如果我取消注释指定的行,它会导致滚动非常慢
我试图用这样的电话来包围电话
dispatch_queue_t coreDataThread = dispatch_queue_create("com.YourApp.YourThreadName", DISPATCH_QUEUE_SERIAL);
dispatch_async(coreDataThread, ^{
Post* post = (Post*)[_fetchedResultsController objectAtIndexPath:indexPath];
NSLog(@"%@", [post valueForKey:@"price"]);
});
但随后需要很长时间 20 秒左右