3

所以我遇到了一个非常令人沮丧的问题......我正在使用 Restkit 从我的 Django 服务器获取对象,并且映射成功完成。那也行!现在,我正在尝试从我的 SQLLite DB 中获取该对象并更改该对象并将其保存回来。例如:

    _managedObjectContext = [RKManagedObjectStore defaultStore].mainQueueManagedObjectContext;


    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"User"];
    fetchRequest.predicate = [NSPredicate predicateWithFormat: @"identifier == 3"];
    NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"identifier" ascending:NO];
    fetchRequest.sortDescriptors = @[descriptor];
    NSError *error = nil;

    NSFetchedResultsController *fetchedResultsController2 = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                                                        managedObjectContext:_managedObjectContext
                                                                          sectionNameKeyPath:nil
                                                                                   cacheName:nil];
    BOOL fetchSuccessful = [fetchedResultsController2 performFetch:&error];
    if (! fetchSuccessful) {
        NSLog(@"%@", error.description);
    }

    PokaUser* user = [[fetchedResultsController2 fetchedObjects]objectAtIndex:0];
    user.firstName = @"NewFirstName";
    BOOL hasSaved = [user.managedObjectContext save:&error];
    NSLog(@"INFO:{%s} CoreData has Saved: %@ (%d)\nerror:%@ | %@ | %@", __FUNCTION__, (hasSaved) ? @"YES" : @"NO", hasSaved, error, [error userInfo],[error localizedDescription]);

我得到以下日志:

CoreData 已保存:YES (1) 错误:(null) | (空) | (无效的)

现在,如果我关闭我的应用程序并重新打开它,(或者甚至自己去检查 Sqllite.db),这些更改不会被保存。我不断得到第一个名字。

以下是我创建 ManagedObjectContext 的方式:

[managedObjectStore createPersistentStoreCoordinator];
NSString *storePath = [RKApplicationDataDirectory() stringByAppendingPathComponent:@"Maindb.sqlite"];

NSString *seedPath = [[NSBundle mainBundle] pathForResource:@"Maindb" ofType:@"sqlite"];
NSError *error;
NSPersistentStore *persistentStore = [managedObjectStore addSQLitePersistentStoreAtPath:storePath fromSeedDatabaseAtPath:seedPath withConfiguration:nil options:nil error:&error];
NSAssert(persistentStore, @"Failed to add persistent store with error: %@", error);

有任何想法吗?!

谢谢!

4

1 回答 1

6

需要调用托管ObjectStore的savePersistentStore方法:[managedObjectStore.mainQueueManagedObjectContext save:&error]; [managedObjectStore.mainQueueManagedObjectContext saveToPersistentStore:&error];

于 2013-03-14T01:11:56.747 回答