Reputation: 16051
I'm just learning core data and mostly coping, but having a little bit of trouble thinking about how I'll implement it.
I want to access the same Core Data from throughout my app. What would be the best way to access it from multiple classes? Would it be recommended to have it as a global variable (normally not recommended in object oriented programming), or to pass it as an instance variable between classes?
Upvotes: 0
Views: 290
Reputation: 5496
Take a look at the MagicalRecord Library. Not only does it make a lot of common fetch requests much more succinct, it also makes it easier to access your managed object context just by using [NSManagedObjectContext defaultContext];
Upvotes: 1
Reputation: 3364
Core data model will be available throughout your app. You can easily access the managed object through out your app. You just need to make an instance of the AppDelegate
class.
Say for example you have stored contacts. You can just use [managedObject valueForKey:@"name"]
in any of the view controllers.
1. Create an instance of the appDelegate
self.theappDel=[[UIApplication sharedApplication] delegate];
2. Get the context,fetch request and entity description.
NSManagedObjectContext*context=[self.theappDel managedObjectContext];
NSEntityDescription*entity=[NSEntityDescription entityForName:@"Contacts" inManagedObjectContext:context];
NSFetchRequest*request=[[NSFetchRequest alloc] init];
[request setEntity:entity];
NSManagedObject*managedObject=nil;
NSError*error=nil;
NSArray*objectList=[context executeFetchRequest:request error:&error];
3. Get the managed object from the array.
if([objectList count]>0)
managedObject=[objectList objectAtIndex:0];
NSLog(@"The name: %@",[managedObject valueForKey:@"name"])
4. Pass the name object using a singleton
(or any convenient method) pattern, in other view controllers that you need it.
Upvotes: 5
Reputation: 90117
Pass the NSManagedObjectContext
instance, or if you just need to handle one object the NSManagedObject
instance, to the next class.
Like it's done in Xcodes Core Data templates.
Upvotes: 1