Ray*_*Ray 12 core-data nsmanagedobjectcontext ios restkit
我使用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");
}
Run Code Online (Sandbox Code Playgroud)
以下是初始化托管数据存储的代码
// 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];
Run Code Online (Sandbox Code Playgroud)
看来保存成功了,在MyClasseTableViewController中我可以读取保存的MyClass条目.然而,在我关闭应用程序并重新启动后.MyClassTableViewController为空,因为获取的结果为空.我使用SQLiteBrowser打开了sqlite文件,MyClass表为空.看起来MyClass实体仅保存在缓存中,但不保存在持久性存储中.我是否需要调用RestKit提供的一些API来保存它?我试图阅读文档,但找不到它.请帮忙.
Ray*_*Ray 24
感谢Tom的领导,我发现RestKit有一个NSManagedObjectContext(RKAdditions),它有一个方法:
- (BOOL)saveToPersistentStore:(NSError **)error
Run Code Online (Sandbox Code Playgroud)
是的,它有逻辑来处理嵌套的托管对象上下文.这是新的代码,只有一行更改,但花了很多时间来找到正确的调用:(
#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");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5120 次 |
| 最近记录: |