应用程序启动时,照片实例会进入内存吗?

时间:2012-08-02 01:03:29

标签: objective-c core-data cs193p

该代码来自斯坦福iOS开发课程的Photomania应用程序。基本上我想知道Photo实体的实例何时被实际提取到内存(或上下文)中。当在表视图控制器中调用此处定义的工厂方法时,会发生这种情况吗?

@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

1 个答案:

答案 0 :(得分:0)

这是“数据库”的“创建照片”或“插入照片”方法。因此,当FlickrFetcher类退出并检索照片时,对于它检索的每张照片都会调用此方法。

此方法首先检查核心数据数据库中是否存在照片,如果不存在,则保存管理对象上下文。

因此,从技术上讲,Photo对象是使用[NSEntityDescription insertNewObjectForEntityForName:inManagedObjectContext:]方法在内存中创建的。