iOS RestKit无法将本地实体保存到数据库
我正在使用RestKit 0.20来解析JSON数据并保存到数据库。 这是一个映射实体SchoolClass,由RestKit处理并保存正常。 我有另一个名为MyClass的实体,它存储我选择的类。这个只在设备上是本地的。iOS RestKit无法将本地实体保存到数据库
这里是我创建并保存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来保存它吗?我试图通读文档,但找不到它。请帮忙。
感谢由汤姆引线,我发现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");
}
很酷..谢谢你的澄清。 – JAHelia 2013-06-21 17:05:16
非常感谢!!!! :(花了很多时间在这里搜索! !谢谢谢谢!!! – crojassoto 2015-05-27 21:57:51
谢谢。长期以来一直在使用该框架,但仍然忘记了这一点。大声笑 – 2015-08-18 12:03:11
您使用嵌套的管理对象上下文吗?如果是这样,你需要保存根据上下文来获取保存到数据存储区的更改 – 2013-03-25 16:23:25
嗨,Tom,感谢您的输入,我在问题中添加了一些代码以显示如何创建存储,我使用RKManagedObjectStore类来完成此操作,并且始终获取managedObjectContext也许RestKit使用的是嵌套的东西,我会深入挖掘你的主导,谢谢。 – Ray 2013-03-25 18:55:26