如何将填充了[UIFont familyNames]
的数组按字母顺序排序? 数组
这里提到的其余答案提到使用@selector(localizedCaseInsensitiveCompare:)
这适用于NSString数组,可是若是你想将它扩展到另外一种类型的对象,并根据'name'属性对这些对象进行排序,你应该这样作相反: spa
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]; sortedArray=[anArray sortedArrayUsingDescriptors:@[sort]];
您的对象将根据这些对象的name属性进行排序。 日志
若是您但愿排序不区分大小写,则须要像这样设置描述符 code
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)];
最简单的方法是提供排序选择器( Apple的文档以获取详细信息) 对象
Objective-C的 排序
sortedArray = [anArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
迅速 ip
let descriptor: NSSortDescriptor = NSSortDescriptor(key: "YourKey", ascending: true, selector: "localizedCaseInsensitiveCompare:") let sortedResults: NSArray = temparray.sortedArrayUsingDescriptors([descriptor])
Apple提供了几种字母排序选择器: 文档
compare:
caseInsensitiveCompare:
localizedCompare:
localizedCaseInsensitiveCompare:
localizedStandardCompare:
迅速 get
var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"] students.sort() print(students) // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
参考 it
一种更强大的方法来排序NSString列表以使用NSNumericSearch之类的东西:
NSArray *sortedArrayOfString = [arrayOfString sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) { return [(NSString *)obj1 compare:(NSString *)obj2 options:NSNumericSearch]; }];
结合SortDescriptor,能够获得以下结果:
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES comparator:^NSComparisonResult(id obj1, id obj2) { return [(NSString *)obj1 compare:(NSString *)obj2 options:NSNumericSearch]; }]; NSArray *sortedArray = [anArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];
-(IBAction)SegmentbtnCLK:(id)sender { [self sortArryofDictionary]; [self.objtable reloadData];} -(void)sortArryofDictionary { NSSortDescriptor *sorter; switch (sortcontrol.selectedSegmentIndex) {case 0: sorter=[[NSSortDescriptor alloc]initWithKey:@"Name" ascending:YES]; break; case 1: sorter=[[NSSortDescriptor alloc]initWithKey:@"Age" ascending:YES]; default: break; } NSArray *sortdiscriptor=[[NSArray alloc]initWithObjects:sorter, nil]; [arr sortUsingDescriptors:sortdiscriptor]; }
使用下面的代码按字母顺序排序:
NSArray *unsortedStrings = @[@"Verdana", @"MS San Serif", @"Times New Roman",@"Chalkduster",@"Impact"]; NSArray *sortedStrings = [unsortedStrings sortedArrayUsingSelector:@selector(compare:)]; NSLog(@"Unsorted Array : %@",unsortedStrings); NSLog(@"Sorted Array : %@",sortedStrings);
如下是控制台日志:
2015-04-02 16:17:50.614 ToDoList[2133:100512] Unsorted Array : ( Verdana, "MS San Serif", "Times New Roman", Chalkduster, Impact ) 2015-04-02 16:17:50.615 ToDoList[2133:100512] Sorted Array : ( Chalkduster, Impact, "MS San Serif", "Times New Roman", Verdana )