【发布时间】:2013-12-24 17:50:49
【问题描述】:
所以我最近切换到了 RestKit 核心数据实现,并且在构建/应用程序启动之间持久化数据时遇到了一些问题 - 即,如果我创建一个对象并保存它,只要应用程序保持打开状态,它就可以正常工作,但一旦我关闭模拟器并重建数据就消失了。我对此做了一些研究,发现了许多这样的 StackOverflow 线程:
Entities saved to RKManagedObjectStore's mainQueueManagedObjectContext disappear on next build
在大多数情况下提供相同的解决方案 - 从 save: 切换到 saveToPersistentStore: - 但不幸的是,即使进行了此更改,我的保存仍然没有持续。我将不胜感激任何帮助!
我的 App Delegate,基本上完全按照基本 RestKit 教程中的配置:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSError *error = nil;
NSURL *modelURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"appName" ofType:@"momd"]];
// NOTE: Due to an iOS 5 bug, the managed object model returned is immutable.
NSManagedObjectModel *managedObjectModel = [[[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL] mutableCopy];
RKManagedObjectStore *managedObjectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:managedObjectModel];
// Initialize the Core Data stack
[managedObjectStore createPersistentStoreCoordinator];
NSPersistentStore __unused *persistentStore = [managedObjectStore addInMemoryPersistentStore:&error];
NSAssert(persistentStore, @"Failed to add persistent store: %@", error);
[managedObjectStore createManagedObjectContexts];
// Set the default store shared instance
[RKManagedObjectStore setDefaultStore:managedObjectStore];
// Override point for customization after application launch.
UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController;
LoginVC *controller = (LoginVC *) navigationController.topViewController;
controller.managedObjectContext = managedObjectStore.mainQueueManagedObjectContext;
return YES;
}
以及实际创建 NSManagedObject 对象的代码:
- (void) theSaveButtonOnTheAddDayVCWasTapped:(AddDaytimeVC *)controller{
[controller.navigationController popViewControllerAnimated:YES];
if([[controller.activityDescriptionTextField text] length] > 0){
NSManagedObjectContext *context = self.managedObjectContext;
Daytime *daytime = [context insertNewObjectForEntityForName:@"Daytime"];
daytime.activityDescription = [controller.activityDescriptionTextField text];
daytime.thoughts = [controller.thoughtsTextField text];
NSError *error;
if (![context saveToPersistentStore:&error]) {
NSLog(@"Error saving context");
}
[self reloadArrayWithCurrentViewActivityType:@"Daytime"];
[[self tableView] reloadData];
}
}
我正在通过标准在视图之间传递 mainQueueManagedObjectContext:
@property (nonatomic, strong) NSManagedObjectContext* managedObjectContext;
在 prepareForSegue 中设置。我最近还做了一个小的模型更改(添加了一个字段)并重新生成了模型对象,如果这可能有帮助的话......不幸的是,我不完全确定它在此之前是否按预期工作。
【问题讨论】:
标签: ios objective-c core-data restkit