帮我对充满NSDictionary对象的NSMutableArray进行排序 - Objective C

6

我有一个NSMutableArray,里面装满了NSDictionary对象。就像这样:

NSMutableArray *names = [[NSMutableArray alloc] init];
for (NSString *string in pathsArray) {
    NSString *path = [NSString stringWithFormat:@"/usr/etc/%@",string];
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:string,@"name",path,@"path",nil];
}

pathsArray不可排序,因此我只能使用其中对象的顺序。我想按字典中键为“name”的对象的字母表顺序对名称数组进行排序。这可以轻松完成吗?还是需要多层枚举?

编辑:我在SO上找到了答案,这个问题在这里:Sort NSMutableArray

NSSortDescriptor类。

NSSortDescriptor *sortName = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
[names sortUsingDescriptors:[NSArray arrayWithObject:sortName]];
[sortName release];

有人想获得免费的答案点数吗?

1个回答

18

可以尝试像这样:

 NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"name"
                                          ascending:YES] autorelease];
 NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
 NSArray *sortedArray = [names sortedArrayUsingDescriptors:sortDescriptors];

 // names : the same name of the array you provided in your question.

你为什么会奇怪地创建变量而不立即给它们赋值呢? - Jamie Chapman
我们如何使这个不区分大小写?因为现在大写字母优先出现.. 例如:ABCabc - Van Du Tran
@VanDuTran 使用 selector:@selector(localizedCaseInsensitiveCompare:)] - Ahmad Kayyali
@AhmadKayyali,这样不行,因为我有一个NSDictionary的NSArray而不是字符串数组 :) - Van Du Tran

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接