gpt4 book ai didi

iphone - 使用 NSComparisonResult 对 CoreData 实体进行排序

转载 作者:太空狗 更新时间:2023-10-30 03:59:42 25 4
gpt4 key购买 nike

我有这个 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

当我这样做时,它可以很好地处理数组:

[someArray sortedArrayUsingSelector:@selector(compareToLocation:)];

但是...我想像这样将它用作 NSFetchedResultsController 的 sortDescriptor:

NSSortDescriptor *sortDistance = [[NSSortDescriptor alloc] 
initWithKey:@"LocationObject"
ascending:YES
selector:@selector(compareToLocation:)];

[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortDistance]];

实体中的“LocationObject”是一个“Transformable”,存储为 CLLocation。

我在 performFetch 上得到这个:

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'unsupported NSSortDescriptor selector: compareToLocation:'

提前感谢您的帮助:)

最佳答案

我假设您正在使用 SQL 存储?

如果是这样,您可以使用的排序描述符有限:

The SQL store, on the other hand, compiles the predicate and sort descriptors to SQL and evaluates the result in the database itself. This is done primarily for performance, but it means that evaluation happens in a non-Cocoa environment, and so sort descriptors (or predicates) that rely on Cocoa cannot work. The supported sort selectors are compare: and caseInsensitiveCompare:, localizedCompare:, localizedCaseInsensitiveCompare:, and localizedStandardCompare: (the latter is Finder-like sorting, and what most people should use most of the time). In addition you cannot sort on transient properties using the SQLite store.

来自 http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/CoreData/Articles/cdPersistentStores.html#//apple_ref/doc/uid/TP40002875-SW11

这意味着您无法执行您在获取请求中尝试执行的操作。最简单的做法是在从数据库中收到结果后对其进行排序,假设您可以将其全部放入内存。

关于iphone - 使用 NSComparisonResult 对 CoreData 实体进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7293996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com