斯坦福iOS7 2013-2014秋Assignment 6的一种答案 #5

本文介绍了一种iOS720课程Assignment6TopRegions的解答方案,通过优化数据库模式来简化查询操作,并提供了具体的代码实现,包括照片加载、摄影师及地区实体的管理。

这篇文章是针对斯坦福iOS7 2013-1014的公开课Assignment 6 Top Regions所进行的解答的第五部分。

Hint 7: Your schema needs to support the specific needs of your application. When you add a photo to the database, feel free to set attributes in Entities other than your Photo entity which can support the querying/sorting you need to do.

Hint 8: With the proper schema, this entire application can be built with very straightforward sort descriptors and predicates. Put your brainpower into designing the right schema rather than building complicated predicates.

Hint 9: For example, you’ll likely want track directly the photographers who are active in a place or region (rather than relying on figuring it out from the photos all the time). 

Hint 10:  With the right schema, you should not need advanced KVC querying like @count. It’s perfectly fine to add an attribute to any entity that keeps track of a count of objects in a relationship if you want. 

填充数据库:


在这里thumbnail为Binary Data类型,lastViewed为Date类型,photoCount和photographerCount为Integer 16类型,其他全为String类型。注意我们使用photoCount和photographerCount,来避免使用复杂的谓词查询数据库。

使用DocumentHelper打开文件,并把photos存储到数据库中:

- (void)application:(UIApplication *)application
performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    [FlickrHelper loadRecentPhotosOnCompletion:^(NSArray *photos, NSError *error) {
        if (error) {
            ...
        } else {
            ...
            [self useDocumentWithFlickrPhotos:photos];
            completionHandler(UIBackgroundFetchResultNewData);
        }
    }];
}
 
- (void)startFlickrFetch
{
    [FlickrHelper startBackgroundDownloadRecentPhotosOnCompletion:^(NSArray *photos, void (^whenDone)()) {
        [self useDocumentWithFlickrPhotos:photos];
        if (whenDone) whenDone();
    }];
}

- (void)useDocumentWithFlickrPhotos:(NSArray *)photos
{
    [DocumentHelper useDocumentWithOperation:^(UIManagedDocument *document, BOOL success) {
        if (success) {
            [Photo loadPhotosFromFlickrArray:photos
                    intoManagedObjectContext:document.managedObjectContext];
            [document saveToURL:document.fileURL
               forSaveOperation:UIDocumentSaveForOverwriting
              completionHandler:nil];
        }
    }];
}

这里我们使用了一个方法,我们新建一个photo 的category,名为Flickr。

创建两个public api

+ (Photo *)photoWithFlickrInfo:(NSDictionary *)photoDictionary
        inManagedObjectContext:(NSManagedObjectContext *)context;
+ (void)loadPhotosFromFlickrArray:(NSArray *)photos // of Flickr NSDictionary
         intoManagedObjectContext:(NSManagedObjectContext *)context;

第一个方法循环photos数组的每一个photo,然后第二个方法查询数据库,如果photo不存在就新建一个,并设置它的属性。

+ (void)loadPhotosFromFlickrArray:(NSArray *)photos // of Flickr NSDictionary
         intoManagedObjectContext:(NSManagedObjectContext *)context
{
    for (NSDictionary *photo in photos) {
        [self photoWithFlickrInfo:photo inManagedObjectContext:context];
    }
}
<pre name="code" class="objc">+ (Photo *)photoWithFlickrInfo:(NSDictionary *)photoDictionary
        inManagedObjectContext:(NSManagedObjectContext *)context
{
    Photo *photo = nil;    
    NSString *unique = [FlickrHelper IDforPhoto:photoDictionary];
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Photo"];
    request.predicate = [NSPredicate predicateWithFormat:@"unique = %@", unique];    
    NSError *error;
    NSArray *matches = [context executeFetchRequest:request error:&error];    
    if (!matches || error || ([matches count] > 1)) {
        // handle error
    } else if ([matches count]) {
        photo = [matches firstObject];
        NSLog(@"%@ already in database", photo.title);
    } else {
        photo = [NSEntityDescription insertNewObjectForEntityForName:@"Photo"
                                              inManagedObjectContext:context];
        photo.unique = unique;
        photo.title = [FlickrHelper titleOfPhoto:photoDictionary];
        photo.subtitle = [FlickrHelper subtitleOfPhoto:photoDictionary];
        photo.imageURL = [[FlickrHelper URLforPhoto:photoDictionary] absoluteString];
        photo.thumbnailURL = [[FlickrHelper URLforThumbnail:photoDictionary] absoluteString];
         
        photo.photographer = [Photographer photographerWithName:[FlickrHelper ownerOfPhoto:photoDictionary]
                                         inManagedObjectContext:context];
         
        photo.region = [Region regionWithPlaceID:[FlickrHelper placeIDforPhoto:photoDictionary]
                                 andPhotographer:photo.photographer
                          inManagedObjectContext:context];
        NSLog(@"%@", photo.title);
    }    
    return photo;
}



上面用到的FlickrHelper方法比较的简单,在.h和.m中实现以下方法:

+ (NSString *)IDforPhotoDictionary:(NSDictionary *)dic;
+ (NSString *)ownerOfPhoto:(NSDictionary *)photo;
+ (NSString *)placeIDforPhoto:(NSDictionary *)photo;

+ (NSURL *)URLforThumbnail:(NSDictionary *)photo;
+ (NSString *)titleOfPhoto:(NSDictionary *)photo;
+ (NSString *)subtitleOfPhoto:(NSDictionary *)photo;
+ (NSURL *)URLforPhoto:(NSDictionary *)photo;

+ (NSURL *)URLforThumbnail:(NSDictionary *)photo
{
    return [FlickrFetcher URLforPhoto:photo format:FlickrPhotoFormatSquare];
}

+ (NSString *)titleOfPhoto:(NSDictionary *)photo
{
    return [photo valueForKeyPath:FLICKR_PHOTO_TITLE];
}

+ (NSString *)subtitleOfPhoto:(NSDictionary *)photo
{
    return [photo valueForKeyPath:FLICKR_PHOTO_DESCRIPTION];
}

+ (NSURL *)URLforPhoto:(NSDictionary *)photo
{
    return [FlickrFetcher URLforPhoto:photo format:FlickrPhotoFormatOriginal];
}
+ (NSString *)placeIDforPhoto:(NSDictionary *)photo
{
    return [photo valueForKeyPath:FLICKR_PHOTO_PLACE_ID];
}

+ (NSString *)IDforPhotoDictionary:(NSDictionary *)dic
{
    return [dic valueForKeyPath:FLICKR_PHOTO_ID];
}

+ (NSString *)ownerOfPhoto:(NSDictionary *)photo
{
    return [photo valueForKeyPath:FLICKR_PHOTO_OWNER];
}

创建一个Photographer的category,名为Create,并在.h和.m中实现以下方法:

+ (Photographer *)photographerWithName:(NSString *)name
                inManagedObjectContext:(NSManagedObjectContext *)context;
+ (Photographer *)photographerWithName:(NSString *)name
                inManagedObjectContext:(NSManagedObjectContext *)context
{
    Photographer *photographer = nil;
    if ([name length]) {
        NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Photographer"];
        request.predicate = [NSPredicate predicateWithFormat:@"name = %@", name];
        NSError *error;
        NSArray *matches = [context executeFetchRequest:request error:&error];
        if (!matches || ([matches count] > 1)) {
            // handle error
        } else if (![matches count]) {
            photographer = [NSEntityDescription insertNewObjectForEntityForName:@"Photographer"
                                                         inManagedObjectContext:context];
            photographer.name = name;
            NSLog(@"%@", photographer.name);
        } else {
            photographer = [matches lastObject];
            NSLog(@"%@ already in database", photographer.name);
        }
    }    
    return photographer;
}

同样,创建一个Region的category, 名为Create,.h和.m中实现以下方法(注意这里,不同的地方时,设置photoCount和photographerCount)

+ (Region *)regionWithPlaceID:(NSString *)placeID
              andPhotographer:(Photographer *)photographer
       inManagedObjectContext:(NSManagedObjectContext *)context;
+ (Region *)regionWithPlaceID:(NSString *)placeID
              andPhotographer:(Photographer *)photographer
       inManagedObjectContext:(NSManagedObjectContext *)context
{
    Region *region = nil;
    if ([placeID length]) {
        NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Region"];
        request.predicate = [NSPredicate predicateWithFormat:@"placeID = %@", placeID];
        NSError *error;
        NSArray *matches = [context executeFetchRequest:request error:&error];
        if (!matches || ([matches count] > 1)) {
            // handle error
        } else if (![matches count]) {
            region = [NSEntityDescription insertNewObjectForEntityForName:@"Region"
                                                         inManagedObjectContext:context];
            region.placeID = placeID;
            region.photoCount = @1;
            [region addPhotographersObject:photographer];
            region.photographerCount = @1;
            NSLog(@"%@", region.placeID);
        } else {
            region = [matches lastObject];
            region.photoCount = @([region.photoCount intValue] + 1);
             
            if (![region.photographers member:photographer]) {
                [region addPhotographersObject:photographer];
                region.photographerCount = @([region.photographerCount intValue] + 1);;
            }
            NSLog(@"%@ already in database", region.placeID);
        }
    }
 
    return region;
}

运行一下,会看到类似这样的结果:“250 photos fetched”



内容概要:本文系统介绍了算术优化算法(AOA)的基本原理、核心思想及Python实现方法,并通过图像分割的实际案例展示了其应用价值。AOA是一种基于种群的元启发式算法,其核心思想来源于四则运算,利用乘除运算进行全局勘探,加减运算进行局部开发,通过数学优化器加速函数(MOA)和数学优化概率(MOP)动态控制搜索过程,在全局探索与局部开发之间实现平衡。文章详细解析了算法的初始化、勘探与开发阶段的更新策略,并提供了完整的Python代码实现,结合Rastrigin函数进行测试验证。进一步地,以Flask框架搭建前后端分离系统,将AOA应用于图像分割任务,展示了其在实际工程中的可行性与高效性。最后,通过收敛速度、寻优精度等指标评估算法性能,并提出自适应参数调整、模型优化和并行计算等改进策略。; 适合人群:具备一定Python编程基础和优化算法基础知识的高校学生、科研人员及工程技术人员,尤其适合从事人工智能、图像处理、智能优化等领域的从业者;; 使用场景及目标:①理解元启发式算法的设计思想与实现机制;②掌握AOA在函数优化、图像分割等实际问题中的建模与求解方法;③学习如何将优化算法集成到Web系统中实现工程化应用;④为算法性能评估与改进提供实践参考; 阅读建议:建议读者结合代码逐行调试,深入理解算法流程中MOA与MOP的作用机制,尝试在不同测试函数上运行算法以观察性能差异,并可进一步扩展图像分割模块,引入更复杂的预处理或后处理技术以提升分割效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值