0

我正在使用 Core Data 和 anNSManagedObject作为对象模型,用于在保存数据之前将数据临时存储在应用程序中。

然后在表格视图中显示所有保存的实例。但是,临时对象也出现在列表中。如何确保我的 tableview 只显示实际保存在数据库中的结果?

- (NSFetchedResultsController *)fetchedResultsController
{
    if (_fetchedResultsController != nil) {
        return _fetchedResultsController;
    }

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    // Edit the entity name as appropriate.
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"State" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];

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

    // Edit the sort key as appropriate.
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timeStamp" ascending:NO];
    NSArray *sortDescriptors = @[sortDescriptor];

    [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.managedObjectContext sectionNameKeyPath:nil cacheName:@"Master"];
    aFetchedResultsController.delegate = self;
    self.fetchedResultsController = aFetchedResultsController;

    NSError *error = nil;
    if (![self.fetchedResultsController performFetch:&error]) {
        // Replace this implementation with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return _fetchedResultsController;
}
4

2 回答 2

3

你可以设置

[fetchRequest setIncludesPendingChanges:NO];

从文档中:

默认值为YES

如果值为NO,则获取请求将跳过检查未保存的更改并仅返回与持久存储中的谓词匹配的对象。

于 2013-10-24T06:47:11.063 回答
0

NSManagedObjectContext NSFetchedResultsController will automatically save the context. So your change is already saved to database before you restore data in tableView

Core Data can manage data in-memory, which is describe as :

Core Data provides an infrastructure for change management and for saving objects to and retrieving them from storage. It can use SQLite as one of its persistent store types. It is not, though, in and of itself a database. (To emphasize this point: you could for example use just an in-memory store in your application. You could use Core Data for change tracking and management, but never actually save any data in a file.)

to solve your problem, you can create another NSManagedObjectContext, which use to save your temporary data. when you want to save these temp data to your database, just create new NSManagedObject and copy the data info from de temp data and save it to your permanent database context

于 2013-10-24T05:22:08.703 回答