-2

我有一个小小的疑问,我有一个包含以下 4 个对象的 NSArray:

Genesis, 1 Kings, leviticus, 2 Kings

我想按字典顺序对这个数组进行排序,就像我想要这样的预期输出

1 Kings, 2 Kings, Genesis, leviticus

如何做到这一点?

4

2 回答 2

6

转到此链接:

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Collections/Articles/Arrays.html#//apple_ref/doc/uid/20000132-SW5

这是苹果文档,你的问题在那里解决了。

查看示例。

//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];

此代码是苹果文档中的一个示例。

我希望它会帮助你。

谢谢,

鹤芒。

于 2012-07-21T09:30:48.237 回答
5

NSString您可以像这样按字母顺序对数组进行排序:

NSArray *sortedArray = [myArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
于 2012-07-21T09:39:12.420 回答