dan*_*dan 4 iphone core-data objective-c
我有这个distanceSorter.h/distanceSorter.m:
@interface CLLocation (DistanceComparison)
- (NSComparisonResult) compareToLocation:(CLLocation *)other;
@end
@implementation CLLocation (DistanceComparison)
- (NSComparisonResult) compareToLocation:(CLLocation *)other {
CLLocation *currentLocation = [[CLLocation alloc] initWithLatitude:[[NSUserDefaults standardUserDefaults] floatForKey:@"lastProcessedLatitude"] longitude:[[NSUserDefaults standardUserDefaults] floatForKey:@"lastProcessedLongitude"]];
CLLocationDistance thisDistance = [self distanceFromLocation:currentLocation];
CLLocationDistance thatDistance = [other distanceFromLocation:currentLocation];
if (thisDistance < thatDistance) { return NSOrderedAscending; }
if (thisDistance > thatDistance) { return NSOrderedDescending; }
return NSOrderedAscending;
}
@end
Run Code Online (Sandbox Code Playgroud)
当我这样做时,它适用于数组:
[someArray sortedArrayUsingSelector:@selector(compareToLocation:)];
Run Code Online (Sandbox Code Playgroud)
但是...我想将它用作NSFetchedResultsController的sortDescriptor,如下所示:
NSSortDescriptor *sortDistance = [[NSSortDescriptor alloc]
initWithKey:@"LocationObject"
ascending:YES
selector:@selector(compareToLocation:)];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortDistance]];
Run Code Online (Sandbox Code Playgroud)
实体中的"LocationObject"是"可转换的"并存储为CLLocation.
我在performFetch上得到这个:
*由于未捕获的异常'NSInvalidArgumentException'终止应用程序,原因:'不支持的NSSortDescriptor选择器:compareToLocation:'
预先感谢您的帮助 :)
我假设你正在使用SQL商店?
如果是这样,您可以使用排序描述符:
另一方面,SQL存储将谓词和排序描述符编译为SQL,并在数据库本身中评估结果.这主要是为了提高性能,但这意味着评估是在非Cocoa环境中进行的,因此依赖Cocoa的排序描述符(或谓词)无法工作.支持的排序选择器是compare:和caseInsensitiveCompare:,localizedCompare:,localizedCaseInsensitiveCompare:和localizedStandardCompare :(后者是类似Finder的排序,以及大多数人应该在大多数时间使用的东西).此外,您无法使用SQLite存储对瞬态属性进行排序.
这意味着您无法在获取请求中执行您尝试执行的操作.最简单的方法是在从数据库接收结果后对结果进行排序,假设您可以将其全部放入内存中.
归档时间: |
|
查看次数: |
2443 次 |
最近记录: |