我真的不明白为什么这给了我这么多麻烦。我正在使用Magical Record的核心数据包装器来创建实体,更新并保存它们。 我能够完美地创建和获取实体,很好。创建的实体很好地被保留,但是,我无法对实体进行更改,并且一旦应用程序终止,这些更改就会持续存在。这是我如何设置魔法记录。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[MagicalRecord setupCoreDataStack];
return YES;
}
当我的应用终止时
- (void)applicationWillTerminate:(UIApplication *)application {
[[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
[MagicalRecord cleanUp];
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
}
我如何创建我的实体
//Create a new payment entity and save it to the persistant data store, dismiss view controller upon saving
PaymentEntity *newPaymentEntity = [PaymentEntity MR_createEntity];
newPaymentEntity.title = self.titleTextField.text;
newPaymentEntity.paymentAmount = self.amountOwedTextField.text;
newPaymentEntity.notes = self.notesTextView.text;
newPaymentEntity.debtors = self.debtorsArray;
newPaymentEntity.createdAt = [NSDate date];
newPaymentEntity.isPayed = NO;
if (self.setDueDateSwitch.on)
newPaymentEntity.dueDate = self.dueDate;
else
newPaymentEntity.dueDate = nil;
[newPaymentEntity.managedObjectContext MR_saveToPersistentStoreWithCompletion:^(BOOL contextDidSave, NSError *error) {
if (error) {
NSLog(@"%@", error.description);
}
else{
[self dismissViewControllerAnimated:YES completion:nil];
}
}];
以及我如何尝试将更改保存到我的实体。
-(void)viewWillDisappear:(BOOL)animated
{
[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {
PaymentEntity *payment = [self.payment MR_inContext:localContext];
payment.amountPayed = self.amountPayedLabel.text;
payment.debtors = self.debtorsArray;
[localContext MR_saveToPersistentStoreAndWait];
}];
[super viewWillDisappear:animated];
}
知道我做错了什么吗?就像我说的,一旦我创建了一个实体,它就会持续存在,但是一旦应用程序终止,我对实体所做的所有更改都不会持久存在。