你需要查找機制來定義季節
NSArray *seasons = @[@"spring", @"summer", @"fall", @"winter"];
NSArray *strings = @[@"2005 fall",@"2007 spring", @"2005 spring", @"2007 winter", @"2005 winter"];
strings = [strings sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {
NSArray *string1Comps = [obj1 componentsSeparatedByString:@" "];
NSArray *string2Comps = [obj2 componentsSeparatedByString:@" "];
NSComparisonResult compareYearResult = [@([string1Comps[0] integerValue]) compare:@([string2Comps[0] integerValue]) ];
if (compareYearResult == NSOrderedSame) {
return [@([seasons indexOfObject:string1Comps[1]]) compare:@([seasons indexOfObject:string2Comps[1]])];
}
return compareYearResult;
}];
結果的排序
(
2005 spring,
2005 fall,
2005 winter,
2007 spring,
2007 winter
)
另一個查找機制可能是一個塊
NSNumber* (^lookUpSeason)(NSString *) = ^(NSString *seasonname){
static NSArray *seasons;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
seasons = @[@"spring", @"summer", @"fall", @"winter"];
});
return @([seasons indexOfObject:seasonname]);
};
這看起來有點麻煩,但使用時會增加可讀性。
return [@([seasons indexOfObject:string1Comps[1]]) compare:@([seasons indexOfObject:string2Comps[1]])];
成爲
return [lookUpSeason(string1Comps[1]) compare:lookUpSeason(string2Comps[1])];
在這兩種情況下,你也可以給查找代碼到比較塊,這會給你機會與在其他地方查找刪除相同的比較。
,如:
NSArray *strings = @[@"2005 fall", @"2007 spring", @"2005 spring", @"2007 winter", @"2005 winter", @"2005 summer", @"2000 hhh"];
NSComparisonResult (^yearAndSeasonComparator)(id,id) = ^NSComparisonResult(NSString *obj1, NSString *obj2) {
NSNumber* (^lookUpSeason)(NSString *) = ^(NSString *seasonname){
static NSArray *seasons;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
seasons = @[@"spring", @"summer", @"fall", @"winter"];
});
return @([seasons indexOfObject:seasonname]);
};
NSArray *string1Comps = [obj1 componentsSeparatedByString:@" "];
NSArray *string2Comps = [obj2 componentsSeparatedByString:@" "];
NSComparisonResult compareYearResult = [@([string1Comps[0] integerValue]) compare:@([string2Comps[0] integerValue]) ];
if (compareYearResult == NSOrderedSame) {
return [lookUpSeason(string1Comps[1]) compare:lookUpSeason(string2Comps[1])];
}
return compareYearResult;
};
strings = [strings sortedArrayUsingComparator:yearAndSeasonComparator];
分配給yearAndSeasonComparator
塊現在可以在其他地方,將相似的字符串進行排序被重用。
我不明白。按字母順序,「秋天」應該在「春天」之前。不按「季節」順序「邏輯」。 – Larme
那麼你最近的問題是什麼,如果年份同樣按名稱降序? –
你想要一個自定義排序,因此你不能使用一個簡單的'sortUsingSelector:'調用。編寫你自己的比較器並使用它。 – rmaddy