0

I have 3 entities saved in core data. I am loading these in several view controllers in the app - sometimes loading data from all 3. Below is how I am loading this data and assign it to an array. Once it is in the array, then I sort, filter, count or whatever I need to do depending on the current page of the app.

if (managedObjectContext == nil) 
{ 
    managedObjectContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext]; 
}
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
[request setReturnsObjectsAsFaults:NO];
NSError *error = nil;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil)
{
    // Handle the error.
    NSLog(@"mutableFetchResults == nil");
}
[self setEventsArray:mutableFetchResults];

The problems I am having are:

  • I don't like to have lots of duplicate code - and this is appearing on every view controller where core data is needed.
  • From one entity, I am saving binary data of images which is causing a lag when I load that data

So, is there a way to load from core data using conditions such as eventId = [NSString stringWithFormat:@"%@", currentEventId]

OR (and probably more suitable) have a separate class that loads the data when the app starts. And then I can access the classes arrays (of the loaded data) to use for the current page. And then just reload the data if I save, edit or delete an object.

Any help is much appreciated.

MPelletier
  • 16,256
  • 15
  • 86
  • 137
Patrick
  • 6,495
  • 6
  • 51
  • 78

1 Answers1

1
  1. Fro your first question, you should look at MagicalRecord which brings Ruby on Rails' Active Record to CoreData. it will shorten clear your core data code.

  2. Pay attention that if your images are not small you should store them on a separate entity with a relationship to your main entity. this should help you with the lag problem since you will load the image trough the relationship only when you will explicitly ask it to. You can see here the answer of Marcus Zarra (wrote a great book on core data). There is always an option that your images are too big for core data.

Hope it helps

Community
  • 1
  • 1
shannoga
  • 19,649
  • 20
  • 104
  • 169
  • Ahh, Yeah. It is likely I will save the images as a separate entity. At the moment they are coming from the camera and then: `UIImageJPEGRepresentation(giftImage, 0.5);` – Patrick Jul 19 '12 at 18:53