我愿意在白天订购我的结果,以便最旧的照片显示在最上面。
我目前正在使用PHAsset fetchAssetsWithMediaType 获取照片:
@property PHFetchResult *photos;
self.photos = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:nil];
理想情况下,我希望按日排序,最早的照片排序。像这样:
[11 Dec]
Photo #20 with creation time 17:00
Photo #21 with creation time 18:30
Photo #22 with creation time 19:00
Photo #23 with creation time 20:40
Photo #24 with creation time 21:00
[10 Dec]
Photo #16 with creation time 10:30
Photo #17 with creation time 11:00
Photo #18 with creation time 12:20
Photo #19 with creation time 13:00
[9 Dec]
Photo #14 with creation time 16:30
Photo #15 with creation time 17:00
我看到我可以使用谓词和一些排序描述符(https://developer.apple.com/reference/photos/phfetchoptions)传递一个PHFetchOptions对象,你能建议我如何指定它们(我相信我应该使用creationDate属性对它们进行排序)这样我和#39;我会得到所需的订单吗?
答案 0 :(得分:6)
您应该使用PHFetchOptions
PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
fetchOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:true]];
PHFetchResult *result = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:fetchOptions];
答案 1 :(得分:0)
PHFetchOptions接受sortDescriptors,但它忽略了自定义比较(我相信,因为它只是执行SQL查询),如此处所写(https://developer.apple.com/reference/photos/phfetchoptions/1624771-sortdescriptors):
照片不支持使用。创建的排序描述符 sortDescriptorWithKey:ascending:comparator:method。
答案是你应该在一个新的NSArray中移动结果,然后在获取它们之后对它们进行排序:
- (void)loadPhotos
{
PHFetchResult *photosResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:nil];
self.photos = [@[] mutableCopy];
for(PHAsset *asset in photosResult){
[self.photos addObject:asset];
}
[self.photos sortUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"creationDate"
ascending:YES
comparator:^NSComparisonResult(NSDate *dateTime1, NSDate *dateTime2) {
unsigned int flags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components1 = [calendar components:flags fromDate:dateTime1];
NSDate* date1 = [calendar dateFromComponents:components1];
NSDateComponents* components2 = [calendar components:flags fromDate:dateTime2];
NSDate* date2 = [calendar dateFromComponents:components2];
NSComparisonResult comparedDates = [date1 compare:date2];
if(comparedDates == NSOrderedSame)
{
return [dateTime2 compare:dateTime1];
}
return comparedDates;
}
]]];
}
我没有使用巨大的相机胶卷测试此解决方案(这里的排序是在内存中完成的,它可能是性能瓶颈),但我希望这可以提供帮助。