我對iOS核心數據很新,我試圖在我的iPad應用程序中使用它。iOS核心數據udpate:更改沒有保存
我有這樣一個模型:
Customer.h
#import <CoreData/CoreData.h>
@interface Customer : NSManagedObject
@property (nonatomic,strong) NSString *name;
@end
Customer.m
#import "Customer.h"
@implementation Customer
@synthesize name;
@end
表視圖控制器顯示所有的客戶在數據庫中。通過選擇客戶詳細信息視圖推賽格瑞開始和客戶設置:如果改變
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
CustomerDetailViewController *detailViewController = (CustomerDetailViewController*) [segue destinationViewController];
detailViewController.customer = [customers objectAtIndex:self.tableView.indexPathForSelectedRow.row];
}
詳細視圖控制器的動作保存應該保存客戶:
- (IBAction)save:(id)sender
{
AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *moc = [delegate managedObjectContext];
self.customer.name = self.nameTextField.text;
NSError *error;
if (![moc save:&error])
{
NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
}
}
雖然名稱改變,所做的更改不會保存:沒有錯誤,但(被零,日誌未顯示錯誤)出現......
此外:
BOOL customerHasChanges = [self.customer hasChanges];
BOOL mocHasChanges = [moc hasChanges];
都是假的!
但是插入新的實體工作正常:
Customer *customer = [NSEntityDescription insertNewObjectForEntityForName:@"Customer" inManagedObjectContext:self.managedObjectContext];
[customer setValue:@"Mars Inc." forKey:@"name"];
NSError *error;
[self.managedObjectContext save:&error];
我在做什麼錯?
在此先感謝您的幫助!!!!!
Luca
你如何檢查它保存了客戶名? – RyanR
我懷疑您的託管對象上下文有問題。嘗試通過託管對象獲取它:'customer.managedObjectContext'。 – Mundi
@RyanR:我的意思是,儘管名稱實際上已經改變(self.customer.name = self.nameTextField.text),實體並沒有改變(例如[customer hasChanges]返回false)。 – Lula