iOS陣列根據key或者類的屬性高階排序
阿新 • • 發佈:2019-01-31
方法一:
NSArray *ary = @[@"a3",@"a1",@"a2",@"a10",@"a24"];NSLog(@"%@",ary);
NSArray *myary = [ary sortedArrayUsingComparator:^(NSString * obj1, NSString * obj2){ return (NSComparisonResult)[obj1 compare:obj2 options:NSNumericSearch];}];
NSLog(@"%@",myary);
結果 ( a3,a1, a2, a10, a24 )
( a1, a2,a3, a10, a24 )
方法二:
NSArray *ary = @[@"a3",@"a1",@"a2",@"a24",@"a14"];
NSLog(@"%@",ary);
NSSortDescriptor *sd1 = [NSSortDescriptor sortDescriptorWithKey:nil ascending:NO];//yes升序排列,no,降序排列NSArray *myary = [ary sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sd1, nil]];
//注意這裡的ary進行排序後會生產一個新的陣列指標,myary,不能在用ary,ary還是保持不變的。
// (a3, a1, a2,a24,a14)
// (a3, a24, a2, a14, a1)
方法三:
[ary sortedArrayUsingSelector:(compare:)];//這個是一直預設升序
sortDescriptorWithKey:此方法可以根據傳入的類屬性或者字典的key--->對應的Value值來進行排序。