Question

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
Was it helpful?

Solution

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.

OTHER TIPS

This is kind of the "create photo" or "insert photo" method for the "database." So when the FlickrFetcher class goes out and retrieves photos, for every photo it retrieves this method is called.

This method first checks to see if the photos exists in the core data database, and if not adds it, and saves the managed object context.

So, technically, the Photo object is created in memory with [NSEntityDescription insertNewObjectForEntityForName: inManagedObjectContext:] method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top