我有一个小疑问,即我有一个包含以下4个对象的NSArray:
Genesis, 1 Kings, leviticus, 2 Kings
我想按照字典顺序对这个数组进行排序,就像我想要一个像这样的预期输出
1 Kings, 2 Kings, Genesis, leviticus
如何实现这一目标?
答案 0 :(得分:6)
转到此链接:
这是Apple文档,您的问题在那里得到解决。
查看示例。
//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];
此代码是Apple文档中的一个示例。
我希望它会对你有所帮助。
谢谢,
Hemang。
答案 1 :(得分:5)
您可以按字母顺序对NSString
数组进行排序:
NSArray *sortedArray = [myArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];