我有一個CoreData實體具有兩個屬性。一個叫'position',另一個叫'positionChange'。它們都是整數,位置屬性是當前位置,positionChange是前一個位置和新位置之間的差異。這意味着positionChange可能是負值。排序核心數據位置變化與排序描述符爲iPhone
現在我想按positionChange進行排序。但我希望它忽視負面價值。目前我正在對它進行降序排序,這會得出結果:2,1,0,-1,-2。 但我要找的是得到這個結果:2,-2,1,-1,0.
關於如何解決這個使用排序描述符的任何想法?
EDIT
我得到2類,一個稱爲的DataManager和另一種含有我的NSNumber類別(positionChange是類型的NSNumber的)。
在DataManager的我有一個方法叫「fetchData:」在那裏我執行與一種描述我的讀取請求:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entity" inManagedObjectContext:managedObjectContext];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"positionChange" ascending:NO selector:@selector(comparePositionChange:)];
[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
我做一些更多的東西的要求,但是這並不有趣爲這個問題。
我的NSNumber類別應完全像您發佈的一個: 在.H:
@interface NSNumber (AbsoluteValueSort)
- (NSComparisonResult)comparePositionChange:(NSNumber *)otherNumber;
@end
而在.M:
@implementation NSNumber (AbsoluteValueSort)
- (NSComparisonResult)comparePositionChange:(NSNumber *)otherNumber
{
return [[NSNumber numberWithFloat:fabs([self floatValue])] compare:[NSNumber numberWithFloat:fabs([otherNumber floatValue])]];
}
@end
當我打電話fetchData我的DataManager對象我得到這個錯誤:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'unsupported NSSortDescriptor selector: comparePositionChange:'
任何想法可能是什麼情況?我在我的DataManager類中包含了我的NSNumber類別頭文件。
你可以在模型中添加一個'absolutePositionChange'字段並用abs(positionChange)'填充它(在'positionChange'的setter中,如果有的話)?你可以在你的排序描述符中使用該字段。 –