我正在尝试在我的 iPad 应用程序中使用 Core Data。
我有一个模型:
客户.h
#import <CoreData/CoreData.h>
@interface Customer : NSManagedObject
@property (nonatomic,strong) NSString *name;
@end
客户.m
#import "Customer.h"
@implementation Customer
@synthesize name;
@end
表视图控制器显示数据库中的所有客户。通过选择客户,将启动详细信息视图推送 segue 并设置客户:
- (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];