I'm trying to use Core Data in my iPad application.
I have a model like:
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
The table view controller shows all the customers in the database. By selecting a customer a details view push segue is started and customer is set:
- (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];
}
In detail view controller the action save should save the customer if changed:
- (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]);
}
}
Although the name is changed, the changes are not saved: no error arises though (error is nil, log not shown)...
Moreover:
BOOL customerHasChanges = [self.customer hasChanges];
BOOL mocHasChanges = [moc hasChanges];
are both false!
However inserting new entities works fine:
Customer *customer = [NSEntityDescription insertNewObjectForEntityForName:@"Customer" inManagedObjectContext:self.managedObjectContext];
[customer setValue:@"Mars Inc." forKey:@"name"];
NSError *error;
[self.managedObjectContext save:&error];