托管对象上下文应该自动保存吗?我认为它正在这样做,因为在应用程序运行期间,数据可以正确获取,但在应用程序启动之间,数据已经消失。
以下是我创建上下文的方法:
+ (NSManagedObjectContext *)createMainQueueGameActivityManagedObjectContext
{
NSManagedObjectContext *managedObjectContext = nil;
NSPersistentStoreCoordinator *coordinator = [self createPersistentStoreCoordinatorWithInvestingGameActivityFilename:InvestingGameActivityDatabaseFilename withDataModelFilename:InvestingGameActivityDataModelFilename];
if (coordinator != nil) {
managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return managedObjectContext;
}
+ (NSPersistentStoreCoordinator *)createPersistentStoreCoordinatorWithInvestingGameActivityFilename:(NSString *)databaseFilename withDataModelFilename:(NSString *)dataModelFilename
{
NSPersistentStoreCoordinator *persistentStoreCoordinator = nil;
NSManagedObjectModel *managedObjectModel = [self createManagedObjectModelWithDataModelFilename:dataModelFilename];
NSString *databasePathComponent = [NSString stringWithFormat:@"%@.%@", databaseFilename, DatabaseFileExtension];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:databasePathComponent];
NSError *error = nil;
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:managedObjectModel];
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
/*
Replace this implementation with code to handle the error appropriately.
*/
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return persistentStoreCoordinator;
}
+ (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
+ (NSManagedObjectModel *)createManagedObjectModelWithDataModelFilename:(NSString *)dataModelFilename
{
NSManagedObjectModel *managedObjectModel = nil;
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:dataModelFilename withExtension:DataModelFileExtension];
managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return managedObjectModel;
}
答案 0 :(得分:2)
托管对象上下文应该自动保存吗?
否。
我认为这样做是因为在应用程序运行期间,数据可以正确获取,但在应用程序启动之间,数据已经消失。
通常将托管对象上下文与便笺本进行比较。您可以从持久性存储中将对象读入上下文,可以将新对象添加到上下文中,也可以在上下文中对对象进行更改。只要应用程序正在运行,所有这些更改都将存在于上下文中。但是当应用程序退出时,上下文消失,您的更改将丢失,除非您将其内容保存回持久存储。为此,您需要调用-save:
方法。