Search code examples
iosobjective-ccore-datansmanagedobjectcontext

Transfer Core Data Over Segue - Objective-C (Xcode)


I am trying to save a few NSStrings to Core Data, and then access them from a UITableView in another view controller. Here is the code I am using to save the strings to Core Data:

- (IBAction)GoBackButton:(id)sender {

    NSManagedObjectContext *context = [self managedObjectContext];

    // Create a new managed object
    NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"Device" inManagedObjectContext:context];
    [newDevice setValue:Title forKey:@"title"];
    [newDevice setValue:Step1 forKey:@"step1"];
    [newDevice setValue:Step2 forKey:@"step2"];
    [newDevice setValue:Step3 forKey:@"step3"];
    [newDevice setValue:img forKey:@"imagename"];


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

    [self performSegueWithIdentifier: @"goBack" sender: self];
    reloadType = @"YES";

    //[self dismissViewControllerAnimated:YES completion:nil];

}

And here is the method I'm using to try and transfer the data back across through the segue:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if([segue.identifier isEqualToString:@"goBack"]){

        [[segue destinationViewController]setManagedObjectContext:self.device];
    }

}

However, the line:

[[segue destinationViewController]setManagedObjectContext:self.device];

brings the error "No known instance method for selector 'setManagedObjectContext:'. I can post more of my Core Data Model creation code if needed to help find a solution to this problem.


Solution

  • Unless your other viewcontroller should also have access to core data methods (like also be able to read and write to your database). I would strongly recommend adding your strings to either an array or a dictionary and pass this instead.

    Anyways, the reason it is not working is because you have to import your other view controller header, and then cast it.

    Something like:

    MyOtherVC *temp = [segue destinationViewController];
    [temp theMethodIWannaUse:theData];
    

    Furthermore, you HAVE to implement it on your other view controller, like if you want to set core data then you have to make your core data object public in the header (or at least the method that you want to use) of your destination view controller.

    Edit:

    The VC to present must have this in the header:

    @property (weak,nonatomic) NSManagedObjectContext *context;
    

    and then just pass it like this on the prepare for segue:

    MyOtherVC *temp = [segue destinationViewController];
    [temp theMethodIWannaUse:theData];
    temp.context = *theContext*;