4

从 apple doc Modifying the Fetch Request我看到可以更改NSFetchRequestfor NSFetchedResultsController。步骤很容易设置。

调用后performFetch:我认为有必要调用reloadData表视图。如何执行这样的调用?

阅读了一些 stackoverflow 主题,我发现调用该方法在大多数情况下应该可以工作。但是有正确的方法吗?

如何以编程方式切换 UITableView 的 NSFetchedResultsController(或其谓词)?TechZen写道:

只需确保在交换控制器之前发送 tableview 本身一个 beginUpdates ,然后在完成后发送一个 endUpdates 。这可以防止表在 FRC 被换出时在窄窗口中请求数据。然后调用 reloadData。

你能具体解释一下这是什么意思吗?

4

1 回答 1

9

假设生成正确提取(某种条件语句)的逻辑在您的 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 变量以指示新值并覆盖设置器以重置 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];
}
于 2012-04-16T21:55:30.983 回答