iOS核心数据更新:未保存更改

时间:2013-10-20 12:58:29

标签: ios objective-c core-data ios7

我正在尝试在我的iPad应用程序中使用Core Data。

我有一个类似的模型:

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

表视图控制器显示数据库中的所有客户。通过选择客户详细信息视图,启动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];

1 个答案:

答案 0 :(得分:4)

您的实施文件中有错误。使用@dynamic代替@synthesize