I am trying to save and retrieve data within multiple views across my application, right now I have it saving the data, and I can retrieve that data, as long as I am within the AppDelegate, but I have added another view to the application, where I would like to retrieve and display the newly stored data, but I am unsure of how I can access core data from within another view, how can I go about achieving that?
Here is what I have thus far,
AppDelegate.m:
// store the data
AppDelegate *app = [UIApplication sharedApplication].delegate;
STUDENT *std = (STUDENT *)[NSEntityDescription insertNewObjectForEntityForName:@"STUDENT" inManagedObjectContext:app.managedObjectContext];
[std setName:@"John"];
[std setNumber:[NSNumber numberWithInteger:1]];
[std setPlace:@"USA"];
[app.managedObjectContext save:nil];
// read the data
NSFetchRequest *req = [[NSFetchRequest alloc]init];
[req setEntity:[NSEntityDescription entityForName:@"STUDENT" inManagedObjectContext:app.managedObjectContext]];
[req setPredicate:[NSPredicate predicateWithFormat:@"name == %@", @"John"]];
STUDENT *stud = [[app.managedObjectContext executeFetchRequest:req error:nil] lastObject];
NSLog(@"%@",stud);
The NSLog outputs what you would expect,
<STUDENT: 0x518b860> (entity: STUDENT; id: 0x518e0a0 <x-coredata://5A6AC621-11C1-4857-82BF-9BEEF258B171/STUDENT/p10> ; data: {
name = John;
number = 1;
place = USA;
})
My other view controller, from where I would like to access the data, is named FirstViewController.m/.h/.xib
, I am quite new to Objective C.