我有一个小小的疑问,我有一个包含以下 4 个对象的 NSArray:
Genesis, 1 Kings, leviticus, 2 Kings
我想按字典顺序对这个数组进行排序,就像我想要这样的预期输出
1 Kings, 2 Kings, Genesis, leviticus
如何做到这一点?
我有一个小小的疑问,我有一个包含以下 4 个对象的 NSArray:
Genesis, 1 Kings, leviticus, 2 Kings
我想按字典顺序对这个数组进行排序,就像我想要这样的预期输出
1 Kings, 2 Kings, Genesis, leviticus
如何做到这一点?
转到此链接:
这是苹果文档,你的问题在那里解决了。
查看示例。
//First create the array of dictionaries
NSString *last = @"lastName";
NSString *first = @"firstName";
NSMutableArray *array = [NSMutableArray array];
NSArray *sortedArray;
NSDictionary *dict;
dict = [NSDictionary dictionaryWithObjectsAndKeys:
@"Jo", first, @"Smith", last, nil];
[array addObject:dict];
dict = [NSDictionary dictionaryWithObjectsAndKeys:
@"Joe", first, @"Smith", last, nil];
[array addObject:dict];
dict = [NSDictionary dictionaryWithObjectsAndKeys:
@"Joe", first, @"Smythe", last, nil];
[array addObject:dict];
dict = [NSDictionary dictionaryWithObjectsAndKeys:
@"Joanne", first, @"Smith", last, nil];
[array addObject:dict];
dict = [NSDictionary dictionaryWithObjectsAndKeys:
@"Robert", first, @"Jones", last, nil];
[array addObject:dict];
//Next we sort the contents of the array by last name then first name
// The results are likely to be shown to a user
// Note the use of the localizedCaseInsensitiveCompare: selector
NSSortDescriptor *lastDescriptor =[[NSSortDescriptor alloc] initWithKey:last
ascending:YES
selector:@selector(localizedCaseInsensitiveCompare:)];
NSSortDescriptor *firstDescriptor =
[[NSSortDescriptor alloc] initWithKey:first
ascending:YES
selector:@selector(localizedCaseInsensitiveCompare:)];
NSArray *descriptors = [NSArray arrayWithObjects:lastDescriptor, firstDescriptor, nil];
sortedArray = [array sortedArrayUsingDescriptors:descriptors];
此代码是苹果文档中的一个示例。
我希望它会帮助你。
谢谢,
鹤芒。
NSString
您可以像这样按字母顺序对数组进行排序:
NSArray *sortedArray = [myArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];