1

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.

Odyss3us
  • 6,457
  • 18
  • 74
  • 112

2 Answers2

1

The app delegate is a singleton of sorts, so you should be able to access it from any view doing

MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];

From there you can call whatever methods you want on it to retrieve and store data..

There is are various questions on where to keep the core data stack to have access through the application, here is one of them. Daniel

Community
  • 1
  • 1
Daniel
  • 22,363
  • 9
  • 64
  • 71
1

You need to import the header of your appDelegate. You will use it to have access to the appDelegate's managed object context. You use that context to fetch the information you need to fetch. You also need to import the header of the class representation of your entity. Doing fetches and insertion is the same process. You might also want to check NSFetchedResultsController documentation to help you out with tableViews and such.

J2theC
  • 4,412
  • 1
  • 12
  • 14