2011-04-24 21 views
1

数组我称之为“游戏”包含自定义类矿山的数组。每个“游戏”都包含一个NSDate。我想根据日期重新排列我的数组,以便它们按从最新到最旧的顺序排列。我怎么能这样做?另外,我的课程'游戏'包含一个NSString。我如何重新排序我的阵列,使游戏按字母顺序排列?如何通过重新排序和NSDates NSString的

回答

8

有一个真正简单的方法来做到这一点,而这与NSSortDescriptor

NSArray *games = ...; //your unsorted array of Game objects 
NSSortDescriptor *sortByDateDescending = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:NO]; 
NSArray *descriptors = [NSArray arrayWithObject:sortByDateDescending]; 

NSArray *sortedGames = [games sortedArrayUsingDescriptors:descriptors]; 

苹果已经写的排序代码。它只需要知道什么属性。这是一个NSSortDescriptor封装。一旦你得到了一个,只需将它提供给数组,然后数组给你一个排序的版本。 (或者,如果您有NSMutableArray,则可以使用-sortUsingDescriptors:就地对其进行排序)

2

该数组必须是一个NSMutableArray对象,然后才能重新排序它,纠正我,如果我错了。

为了你需要写在游戏类的自定义排序方法数组排序。喜欢的东西:

- (NSComparisonResult)compareGameByString:(Game *)otherGame 
{ return [[self stringValue] caseInsensitiveCompare:[otherGame stringValue]]; } 

然后:

[yourMutableArray sortUsingSelector:@selector(compareGameByString:)]; 

比较日期:

- (NSComparisonResult)compareByDate:(Game *)otherGame 
{ 
    if([otherGame isKindOfClass:[Game class]]) 
    { 
     // NSdate has a convenient compare method 
     return [[self dateValue] compare:[otherGame dateValue]]; 
    } 

还要注意的是,在你的数组包含的对象,并没有这些选择做出反应,因此事件一个对象,它是不是一个游戏对象,你会得到一个例外,那您的应用程序可能会破坏

+1

可以使用' - [NSArray sortedArrayUsingSelector:]'对常规数组进行排序。或者您可以使用'NSSortDescriptor',而不必担心编写比较代码。 – 2011-04-25 00:31:32

相关问题