The code is from Stanford iOS developing course's Photomania app. Basically I want to know when instances of Photo entity are actually fetched into memory (or context). Is that happen when the factory method defined here is called in a table view controller?
@interface Photo (Flickr)
+ (Photo *)photoWithFlickrInfo:(NSDictionary *)flickrInfo
inManagedObjectContext:(NSManagedObjectContext *)context;
@end
@implementation Photo (Flickr)
+ (Photo *)photoWithFlickrInfo:(NSDictionary *)flickrInfo
inManagedObjectContext:(NSManagedObjectContext *)context
{
Photo *photo = nil;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Photo"];
request.predicate = [NSPredicate predicateWithFormat:@"unique = %@", [flickrInfo objectForKey:FLICKR_PHOTO_ID]];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"title" ascending:YES];
request.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSError *error = nil;
NSArray *matches = [context executeFetchRequest:request error:&error];
if (!matches || ([matches count] > 1)) {
// handle error
} else if ([matches count] == 0) {
photo = [NSEntityDescription insertNewObjectForEntityForName:@"Photo" inManagedObjectContext:context];
photo.unique = [flickrInfo objectForKey:FLICKR_PHOTO_ID];
photo.title = [flickrInfo objectForKey:FLICKR_PHOTO_TITLE];
photo.subtitle = [flickrInfo valueForKeyPath:FLICKR_PHOTO_DESCRIPTION];
photo.imageURL = [[FlickrFetcher urlForPhoto:flickrInfo format:FlickrPhotoFormatLarge] absoluteString];
photo.whoTook = [Photographer photographerWithName:[flickrInfo objectForKey:FLICKR_PHOTO_OWNER] inManagedObjectContext:context];
} else {
photo = [matches lastObject];
}
return photo;
}
@end
The photo is loaded into memory when you call this method. CoreData probably does some caching such that subsequent fetches will not have to go to the storage backend, but this is definitely where the magic happens.
You should read up more on CoreData. It is a huge framework, but a solid understanding of it will take you a long way in designing efficient and sensible storage solutions for Cocoa apps.