Q:

Core Data: unnecessary queries?

Good evening,
I need some help with Core Data. I have two entities, Images & Album (ImageGroup in code), that have a many-to-many relationship. Each image can have many Albums and an Album can have many images. 
In the application, the user can create an Album. Once the album is created, all the new pictures get added to that album. This is working fine. 
But now I have a question regarding the fetch request in Core Data. Please have a look at my current "fetch" code:
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSError *error;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"ImageGroup" inManagedObjectContext:context];
[fetchRequest setEntity:entity];

NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
[fetchRequest release];

// Load all the other albums
for (ImageGroup *group in fetchedObjects) {
    NSString *albumName = group.name;
    NSSet *groupSet = group.group;
    for (Images *image in groupSet) {
        NSLog(@"imageTN: %@", image.nameTN);
    }
}

This is working fine as well. However, during the "for in" loop for groupSet, a select query is executed for EACH step in the loop. This is fine if you only have a few images, however, if you have 1000+ images stored, this code would execute 1000+ queries.
Is there a way to load all the images that are associated with the Album in one single query?
(SELECT * from Images WHERE album_ID = ? something like that).
This is the first time i'm using Core Data and not sqlite. Any help is truly appreciated.

A:

This is possible, if you don't go through the set, or you prefetch the images in group (since your current fetch request fetch ALL ImageGroup entities, you probably should avoid that).
To prefetch the to-many relationship add to your request:
[fetchRequest setRelationshipsForPrefetching:@[@"group"]]
i would also add:
[fetchRequest setIncludesPropertyValues:YES] and:
[fetchRequest setReturnsObjectsAsFaults:NO]
If you want to issue a single request per ImageGroup you could use:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Images"];
[fetchRequest setIncludesPropertyValues:YES]
[fetchRequest setReturnsObjectsAsFaults:NO]
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"%@ IN <albom set>",group.objectID]; //not tested

note: by the end of the external loop you have faulted (allocated in memory) all alboms and all their attached images.
You should fault each ImageGroup you are done with to keep memory peeks at bay.

