3

从apple doc Modifying the Fetch Request我看到可以将NSFetchRequest更改为NSFetchedResultsController。步骤很容易设置。更改NSFetchedResultsController的提取请求和重新加载表数据的食谱

调用performFetch:后我觉得有必要在表视图上调用reloadData。如何执行此类调用?

阅读一些stackoverflow主题,我已经看到调用该方法应该在大多数情况下工作。但是有没有正确的方法来做到这一点?

How to switch UITableView's NSFetchedResultsController (or its predicate) programmatically?TechZen写道:

只要确保你之前交换 控制器和那么endUpdates发送tableview中本身就是一个beginUpdates当您完成。当 FRC被换出时,此 可防止表在窄窗口中询问数据。然后调用reloadData。

你能解释一下究竟是什么意思?

回答

8

假设生成正确提取(某种条件语句)的逻辑位于NSFetchedResultsController实例的getter中。然后,它是很容易

self.fetchedResultsController = nil; // this destroys the old one 
[self.tableview reloadData]; 
// when the table view is reloaded the fetchedResultsController will be lazily recreated 

编辑:添加的东西,我已经做了完整的代码示例。基本上我有一个NSDictionary entityDescription,它保存值来自定义创建NSFetchedResultsController。如果我想更改fetchRequest,则更改我的entityDescription变量以指示新值并覆盖setter以重置fetchedResultsController并重新加载表。它给你的基本想法。

- (NSFetchedResultsController *)fetchedResultsController 
{ 
    if (__fetchedResultsController != nil) { 
     return __fetchedResultsController; 
    } 
    if (self.entityDescription == nil) { 
     return nil; 
    } 
    // Set up the fetched results controller. 
    // Create the fetch request for the entity. 
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:[self.entityDescription objectForKey:kEntityName]]; 

    // Set the batch size to a suitable number. 
    [fetchRequest setFetchBatchSize:20]; 

    // Edit the sort key as appropriate. 
    if ([[self.entityDescription objectForKey:kEntitySortField] isEqualToString:@"null"] == NO) { 
     NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:[self.entityDescription objectForKey:kEntitySortField] ascending:YES]; 
     NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil]; 
     [fetchRequest setSortDescriptors:sortDescriptors]; 
    } 

    // Edit the section name key path and cache name if appropriate. 
    // nil for section name key path means "no sections". 
    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest 
                           managedObjectContext:self.moc sectionNameKeyPath:nil cacheName:nil]; 
    aFetchedResultsController.delegate = self; 
    self.fetchedResultsController = aFetchedResultsController; 

    NSError *error = nil; 
    if (![self.fetchedResultsController performFetch:&error]) { 
     NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
     abort(); 
    } 

    return __fetchedResultsController; 
} 

- (void)setEntityDescription:(NSDictionary *)entityDescription 
{ 
    _entityDescription = entityDescription; 
    self.fetchedResultsController = nil; 
    [self.tableView reloadData]; 
} 
+0

谢谢您的回复。你能更好地解释你的意思吗?干杯。 – 2012-04-17 08:38:57

+0

我扩大了我的答案 – agilityvision 2012-04-17 14:12:00

相关问题