你如何使用NSSortDescriptor对NSNumber进行排序?

时间:2009-09-25 01:11:40

标签: iphone nsnumber nssortdescriptor

我在使用NSSortDescriptor排序NSNumber时遇到问题。无论出于何种原因,它都不会排成正确的顺序。我做错了什么?

- (NSNumber *)sortNumber {

NSNumber *sum = [NSNumber numberWithFloat:([self.capacity floatValue] / [self.availability floatValue])];

return sum;
}

它在xcdataModel中定义为Int32,并由此类调用以进行排序。

- (NSFetchedResultsController *)fetchedResultsController {
if (fetchedResultsController == nil) {
    NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease];
    [fetchRequest setReturnsObjectsAsFaults:NO];  
    [fetchRequest setEntity:[NSEntityDescription entityForName:@"Event" inManagedObjectContext:managedObjectContext]];
    NSArray *sortDescriptors = nil; 
} if ([fetchSectioningControl selectedSegmentIndex] == 0) {
        sortDescriptors = [NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:@"sortNumber" ascending:YES selector:@selector(compare:)] autorelease]];
}
[fetchRequest setSortDescriptors:sortDescriptors];
编辑:是的,在白天的冷光下,这需要更多的解释。我会尝试解释这个项目。这是一个CoreData应用程序,值'capacity'和'availability'来源于使用SAX解析XML文件并将它们附加到托管对象模型,它们被定义为字符串,最初它们在XML中是数字。

然后在一个类中定义它们,其中上面的计算已经完成并附加到相同的对象模型(如果上面的代码是正确的,那么这可能是问题所在?)。所有这些都是为了获得我想用来对TableView进行排序的百分比值。 (顺便说一句,我意识到他们需要交换,oops)第二位代码是使用NSFetchResultsController和ManagedObjectContext发生这种情况。我知道这一点有效,因为我也是通过设置为selectSegmentIndex == 0等的其他属性对此列表进行排序。它们都排序正确。

我希望这更有意义。

1 个答案:

答案 0 :(得分:0)

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"sortNumber" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];

[request setSortDescriptors:sortDescriptors];

您可以在不调用比较方法的情况下使用NSSortDescriptor。它会按照你想要的顺序排序。