所以我遇到了一个非常令人沮丧的问题......我正在使用Restkit从我的Django服务器获取对象,并且映射已成功完成。那样就好!现在,我试图从我的SQLLite数据库中获取该对象并更改该对象并将其保存回来。例如:
_managedObjectContext = [RKManagedObjectStore defaultStore].mainQueueManagedObjectContext;
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"User"];
fetchRequest.predicate = [NSPredicate predicateWithFormat: @"identifier == 3"];
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"identifier" ascending:NO];
fetchRequest.sortDescriptors = @[descriptor];
NSError *error = nil;
NSFetchedResultsController *fetchedResultsController2 = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:_managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
BOOL fetchSuccessful = [fetchedResultsController2 performFetch:&error];
if (! fetchSuccessful) {
NSLog(@"%@", error.description);
}
PokaUser* user = [[fetchedResultsController2 fetchedObjects]objectAtIndex:0];
user.firstName = @"NewFirstName";
BOOL hasSaved = [user.managedObjectContext save:&error];
NSLog(@"INFO:{%s} CoreData has Saved: %@ (%d)\nerror:%@ | %@ | %@", __FUNCTION__, (hasSaved) ? @"YES" : @"NO", hasSaved, error, [error userInfo],[error localizedDescription]);
我得到以下日志:
CoreData已保存:是(1) 错误:(null)| (null)| (空)
现在,如果我关闭我的应用程序并重新打开它,(或者甚至自己检查Sqllite.db),则不会保存更改。我一直得到第一个名字。
以下是我创建ManagedObjectContext的方法:
[managedObjectStore createPersistentStoreCoordinator];
NSString *storePath = [RKApplicationDataDirectory() stringByAppendingPathComponent:@"Maindb.sqlite"];
NSString *seedPath = [[NSBundle mainBundle] pathForResource:@"Maindb" 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);
有什么想法吗?!
谢谢!
答案 0 :(得分:6)
有必要调用托管ObjectStore的savePersistentStore方法:[managedObjectStore.mainQueueManagedObjectContext save:& error]; [managedObjectStore.mainQueueManagedObjectContext saveToPersistentStore:& error];