//創建一個數組 NSArray *array = @[@"one", @"two", @"three", @"four", @"six"]; //創建一個排序條件,也就是一個NSSortDescriptor對象 //其中第一個參數為數組中對象要按照什么屬性來排序(比如自身、姓名,年齡等) //第二個參數為指定排序方式是升序還是降序 //ascending 排序的意思,默認為YES 升序 NSSortDescriptor *des = [[NSSortDescriptor alloc] initWithKey:@"self" ascending:YES]; NSArray *newArray = [array sortedArrayUsingDescriptors:@[des]]; NSLog(@"%@",newArray);
可以用sortedArrayUsingDescriptors:方法實現把多個排序條件放到數組中,實現多條件排序,按數組先后順序,先加入的優先級高
//創建一個Person類 Person *p1 = [[Person alloc] initWithName:@"zhonger" age:@"19"]; Person *p2 = [[Person alloc] initWithName:@"zhubada" age:@"11"]; Person *p3 = [[Person alloc] initWithName:@"zhubada" age:@"1"]; Person *p4 = [[Person alloc] initWithName:@"zhubada" age:@"33"]; Person *p5 = [[Person alloc] initWithName:@"hehehe" age:@"38"]; NSArray *person = @[p1, p2, p3, p4, p5]; NSSortDescriptor *des1 = [[NSSortDescriptor alloc]initWithKey:@"name" ascending:YES]; NSSortDescriptor *des2 = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:NO]; NSArray *newArray1 = [person sortedArrayUsingDescriptors:@[des1,des2]]; NSLog(@"%@",newArray1);
使用NSSortDesriptor進行數組排序有三步
1.創建一個用來排序的數組
2.創建一個排序條件,初始化中需要指定按照數組中對象的什么屬性進行排序,升序或者降序
3.數組根據排序條件進行排序,得到一個排序之后的數組(如果是可變數組,不會生成新數組,還是本身)
使用的sortedArrayUsingSelecor:的方法,就不需要創建NSSortDescriptor
NSArray *strArray = @[@"zhonger", @"zhubada", @"qiuxiang", @"tangbohu", @"honghuang"]; NSArray *nesStr = [strArray sortedArrayUsingSelector:@selector(compare:)]; //SEL 只能用@selector(方法名)給定,並且,如果數組使用這個數組進行排序,此方法必須是返回值為NSComparisionResult NSLog(@"newStr is %@",nesStr); NSArray *personNewArray = [person sortedArrayUsingSelector:@selector(compareByName:)]; NSLog(@"--%@",personNewArray);