iOS對存放對象的數(shù)組排序
//我們將要排序的對象是一個Persion類,如下定義:
@interface Person : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) NSDate *dateOfBirth;
@end
//而數(shù)組中包含如下內(nèi)容:
//Smith 03/01/1984
//Andersen 16/03/1979
//Clark 13/09/1995
1.使用NSComparator進行排序
typedef NSComparisonResult (^NSComparator)(id obj1, id obj2);
上面的參數(shù)(obj1、obj2)就是我們將要做比較的對象。block返回的結(jié)果為NSComparisonResult類型來表示兩個對象的順序。
要對整個數(shù)組做排序,則需要使用NSArray的sortArrayUsingComparator:方法,如下代碼所示:
NSArray *sortedArray = [self.persons sortedArrayUsingComparator:^NSComparisonResult(Person *p1, Person *p2){
//對數(shù)組進行排序(升序)
return [p1.dateOfBirth compare:p2.dateOfBirth];
//對數(shù)組進行排序(降序)
// return [p2.dateOfBirth compare:p1.dateOfBirth];
}];
2.使用NSDescriptor進行排序
Sort descriptor不僅可以用來對數(shù)組進行排序,還能指定element在table view中的排序,以及Core Data中對fetch request返回的數(shù)據(jù)做排序處理。通過sort descriptor可以很方便的對數(shù)組進行多個key的排序。下面來看看如何對我們的數(shù)組做surname排序,然后在進行name排序:
NSSortDescriptor *firstDescriptor = [[NSSortDescriptor alloc] initWithKey:@"dateOfBirth" ascending:YES];
NSSortDescriptor *secondDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObjects:firstDescriptor, secondDescriptor, nil];
NSArray *sortedArray = [self.persons sortedArrayUsingDescriptors:sortDescriptors];
上面代碼的排序結(jié)果如下所示:
Andersen Jane
Clark Anne
3.使用selector進行排序
當面,我們也可以定義自己的方法進行兩個對象做比較,并將該方法用于數(shù)組排序。comparator消息會被發(fā)送到數(shù)值中的每個對象中,并攜帶數(shù)組 中另外的一個對象當做參數(shù)。自定義的的方法的返回結(jié)果是這樣的:如果本身對象小于參數(shù)中的對象,就返回NSOrederedAscending,相反,則 返回NSOrderedDescending,如果相等,那么返回NSOrderedSame。如下代碼所示:
- (NSComparisonResult)compare:(Person *)otherPerson {
return [self.dateOfBirth compare:otherPerson.dateOfBirth];
}
這個方法定義在Person類中,用來對person的生日進行排序。
//日期去重
NSSet *set = [NSSet setWithArray:@[@"2019-05-23 11:48:17",@"2019-05-23 11:48:32"]];
NSArray *userArray = [set allObjects];
//重新降序排序
NSSortDescriptor *sd1 = [NSSortDescriptor sortDescriptorWithKey:nil ascending:NO];//yes升序排列,no,降序排列
NSArray *descendingDateArr = [userArray sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sd1, nil]];