Frederic
Frederic

Reputation: 497

fetching coredata in objective c

I've been trying to learn Objective C and been following a tutorial teaching using CoreData.

I have made a viewcontroller with a cancel and save button, the tutorial provides the code, however after copying and pasting the code, I get errors.

Could it be that this tutorial i'm following is several years old, and in some way this code is outdated?

The error are from "NSManagedObject *newDevice...." to "if (![context save:&error])"

enter image description here

This is my code:

#import "DeviceDetailViewController.h"

@interface DeviceDetailViewController ()

@end

@implementation DeviceDetailViewController

- (NSManagedObjectContext *)managedObjectContext {
    NSManagedObjectContext *context = nil;
    id delegate = [[UIApplication sharedApplication] delegate];
    if ([delegate performSelector:@selector(managedObjectContext)]) {
        context = [delegate managedObjectContext];
    }
    return context;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
     #pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)cancell:(id)sender {

    [self dismissViewControllerAnimated:YES completion:nil];
}



- (IBAction)save:(id)sender {

    NSManagedObjectContext *context = [self managedObjectContext];

    // Create a new managed object
    NSManagedObject *newDevice = [NSEntityDescription       insertNewObjectForEntityForName:@"Device" inManagedObjectContext:context];
    [newDevice setValue:self.nameTextField.text forKey:@"name"];
    [newDevice setValue:self.versionTextField.text forKey:@"version"];
    [newDevice setValue:self.companyTextField.text forKey:@"company"];

    NSError *error = nil;
    // Save the object to persistent store
    if (![context save:&error]) {
        NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
    }

    [self dismissViewControllerAnimated:YES completion:nil];

}


@end

Upvotes: 1

Views: 118

Answers (1)

Tom Harrington
Tom Harrington

Reputation: 70976

It looks like you haven't imported the Core Data framework header file. You need a line at the top of the file reading

#import <CoreData/CoreData.h>

Upvotes: 2

Related Questions