当我尝试更新核心数据对象时,我遇到了一个奇怪的错误(null错误)。第一次保存对象(餐厅)时,它可以完美保存。但是,当我尝试更新餐厅时 - 这就是我遇到错误的地方:
RestaurantDetailViewController.h:
@class Restaurant;
@interface RestaurantDetailViewController : UITableViewController <UINavigationControllerDelegate, UITextViewDelegate, CuisinePickerViewControllerDelegate>
@property (nonatomic, strong) IBOutlet UITextView *reviewTextView;
@property (nonatomic, strong) IBOutlet UILabel *cuisineLabel;
@property (nonatomic, strong) IBOutlet UILabel *dateLabel;
@property (strong, nonatomic) IBOutlet UILabel *addressLabel;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *address;
@property (nonatomic, assign) double longitude;
@property (nonatomic, assign) double latitude;
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
@property (nonatomic, strong) NSManagedObjectContext *managedObjectContext;
@property (nonatomic, strong) Restaurant *restaurantToEdit;
- (IBAction)done:(id)sender;
- (IBAction)cancel:(id)sender;
@end
RestaurantDetailViewController.m:
- (void)viewDidLoad
{
[super viewDidLoad];
if (self.restaurantToEdit != nil) {
self.navigationItem.title = @"Edit Restaurant";
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self
action:@selector(done:)];
}
date = [NSDate date];
self.navigationItem.title = name;
self.reviewTextView.text = reviewText;
self.cuisineLabel.text = @"No Cuisine selected";
self.addressLabel.text = address;
self.dateLabel.text = [self formatDate:date];
- (IBAction)done:(id)sender
{
Restaurant *restaurant = nil;
if (self.restaurantToEdit != nil) {
restaurant = self.restaurantToEdit;
} else {
restaurant = [NSEntityDescription insertNewObjectForEntityForName:@"Restaurant" inManagedObjectContext:self.managedObjectContext];
}
restaurant.restaurantName = name;
restaurant.restaurantReview = reviewText;
restaurant.cuisine = cuisineType;
restaurant.latitude = [NSNumber numberWithDouble:self.latitude];
restaurant.longitude = [NSNumber numberWithDouble:self.longitude];
restaurant.date = date;
restaurant.address = address;
NSError *error;
if (![self.managedObjectContext save:&error]) {
NSLog(@"Error %@", error);
abort();
return;
}
[self performSelector:@selector(closeScreen) withObject:nil afterDelay:0.6];
}
- (void)setRestaurantToEdit:(Restaurant *)newRestaurantToEdit
{
if (restaurantToEdit != newRestaurantToEdit) {
restaurantToEdit = newRestaurantToEdit;
reviewText = restaurantToEdit.restaurantReview;
cuisineType = restaurantToEdit.cuisine;
date = restaurantToEdit.date;
address = restaurantToEdit.address;
}
}
答案 0 :(得分:3)
看来,在prepareForSegue方法中,如果是更新,则不会设置controller.managedObjectContext属性。你需要添加
controller.managedObjectContext = self.managedObjectContext;
因此无论是新餐厅还是更新,都会被称为。