12

我正在使用 RestKit 0.20 解析 JSON 数据并保存到数据库。这是一个映射实体SchoolClass,由RestKit处理并保存良好。我有另一个名为 MyClass 的实体,它存储我选择的类。这仅在设备上是本地的。

这是我创建并保存 MyClass 实体的代码

 NSManagedObjectContext *managedObjCtx = [RKManagedObjectStore defaultStore].mainQueueManagedObjectContext;
 MyClass* course = [managedObjCtx insertNewObjectForEntityForName:@"MyClass"];

 .. set the data for course here

 NSError *executeError = nil;
 if(![managedObjCtx save:&executeError]) {
      NSLog(@"Failed to save to data store");
 }

这是初始化托管数据存储的代码

  // Initialize managed object store
    NSManagedObjectModel *managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
    RKManagedObjectStore *managedObjectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:managedObjectModel];
    objectManager.managedObjectStore = managedObjectStore;

   /**
     Complete Core Data stack initialization
     */
    [managedObjectStore createPersistentStoreCoordinator];
    NSString *storePath = [RKApplicationDataDirectory() stringByAppendingPathComponent:@"RKMainDb.sqlite"];
    NSString *seedPath = [[NSBundle mainBundle] pathForResource:@"RKSeedDatabase" 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);

    // Create the managed object contexts
    [managedObjectStore createManagedObjectContexts];

    // Configure a managed object cache to ensure we do not create duplicate objects
    managedObjectStore.managedObjectCache = [[RKInMemoryManagedObjectCache alloc] initWithManagedObjectContext:managedObjectStore.persistentStoreManagedObjectContext];

看来保存是成功的,在 MyClasseTableViewController 中我可以读取保存的 MyClass 条目。但是,在我关闭应用程序并重新启动后。MyClassTableViewController 是空的,因为获取的结果是空的。我使用 SQLiteBrowser 打开了 sqlite 文件,而 MyClass 表是空的。看起来 MyClass 实体只保存在缓存中,而不是持久存储中。我需要调用RestKit提供的一些API来保存它吗?我试图通读文档但找不到它。请帮忙。

4

1 回答 1

24

感谢 Tom 的带领,我发现 RestKit 有 NSManagedObjectContext (RKAdditions),它有一个方法:

- (BOOL)saveToPersistentStore:(NSError **)error

是的,它确实具有处理嵌套托管对象上下文的逻辑。这是有效的新代码,只更改了一行,但花了很多时间来找到正确的调用:(

#import "NSManagedObjectContext+RKAdditions.h"
     NSManagedObjectContext *managedObjCtx = [RKManagedObjectStore defaultStore].mainQueueManagedObjectContext;
     MyClass* course = [managedObjCtx insertNewObjectForEntityForName:@"MyClass"];

     .. set the data for course here

     NSError *executeError = nil;
     if(![managedObjCtx saveToPersistentStore:&executeError]) {
          NSLog(@"Failed to save to data store");
     }
于 2013-03-25T20:08:36.803 回答