2011-06-30 42 views
0

我面临排序问题。该场景解释为:我有一个类(假设的人),它有4个属性(firstName,lastName,Address,salary),我创建了它的对象并创建了一个所有属性的集合,并将这个对象放在一个NSMutableArray中,等等。所以在数组的每一个索引中,我都有一个对象(即4个属性的集合)。现在我想根据薪水对这个数组进行排序,任何人都可以帮我解决这个问题,会很感激。,排序自定义类对象的数组

+0

标题很混乱,我认为这是关于类的数组。 – 2011-06-30 06:53:29

回答

0

请参阅NSArray的文档。它有几种排序方法。搜索单词“排序”,你会发现他们。 (你会想要基于块或功能的API)。

0

使用本

NSSortDescriptor *sorter = [[[NSSortDescriptor alloc] initWithKey:@"salary" ascending:YES] autorelease]; 
NSArray *sortDescriptors = [NSArray arrayWithObject: sorter]; 
    [yorArrary sortUsingDescriptors:sortDescriptors]; 
+0

@Ishu,Maulik: 我已经实现了这样的,但我的程序给我的例外“线程1:程序接收到的信号:SIGABRT”并坠毁 NSSortDescriptor *分拣= [[[NSSortDescriptor页头​​] initWithKey:@“工资“升序:YES] autorelease]; NSArray * sortDescriptors = [NSArray arrayWithObject:sorter]; [appDelegate.ContactArray sortUsingDescriptors:sortDescriptors]; 关于此行为的任何想法? –

+0

给日志消息显示你得到的任何异常。 – Ishu

+0

Ishu其实我不确切知道错误是什么,在何时到达这一行 [appDelegate.ContactArray sortUsingDescriptors:sortDescriptors]; 程序崩溃,只是接收到这条日志消息“抛出'NSException'的实例后终止调用” –

0

要么你实现你的对象比较法:

- (NSComparisonResult)compare:(Person *)otherObject { 
return [self.birthDate compare:otherObject.birthDate]; 
} 

NSArray *sortedArray; 
sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(compare:)]; 

或者平时甚至更好:(NSSortDescriptor的默认排序选择是比较:)

NSSortDescriptor *sortDescriptor; 
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"birthDate" 
              ascending:YES] autorelease]; 
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor]; 
NSArray *sortedArray; 
sortedArray = [drinkDetails sortedArrayUsingDescriptors:sortDescriptors];