简体   繁体   English

如何使用NSArray按字母顺序对NSDictionary中的值进行排序?

[英]How can I alphabetically sort the values in my NSDictionary with an NSArray?

I have an NSDictionary which contains several arrays with several strings in them. 我有一个NSDictionary,其中包含几个包含多个字符串的数组。 I want to put all strings under each array in one single array. 我想把每个数组下的所有字符串放在一个单独的数组中。 How can I receive all the strings at once? 我怎样才能一次收到所有字符串? I've tried this: 我试过这个:

NSMutableArray *mutarr = [[NSMutableArray alloc] initWithObjects:[self.firstTableView allValues], nil];
NSArray *mySorted = [[NSArray alloc]init];
mySorted = [mutarr sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];

NSLog(@"First table view values: %@", mySorted);

NOTE: self.firsttableview is a NSDictionary like this: 注意:self.firsttableview是一个像这样的NSDictionary:

NSString *path = [[NSBundle mainBundle] pathForResource:@"firstTableView" ofType:@"plist"];

self.firstTableView = [NSDictionary dictionaryWithContentsOfFile:path];

EFFECT: This gives me a list in NSLog, but it isn't in alphabetic order. 效果:这给了我NSLog中的列表,但它不是按字母顺序排列的。

You are initializing your mutarr with one object which is the array returned by allValues on your dictionary. 您正在使用一个对象初始化您的mutarr,该对象是您的字典上allValues返回的数组。 Instead try this: 而是试试这个:

NSMutableArray* mutarr = [NSMutableArray array];

for (NSArray* array in self.firstTableView.allValues) {
    [mutarr addObjectsFromArray:array];
}

Your code is going to mean that mutarr is an array containing an array of arrays, not an array of strings. 你的代码意味着mutarr是一个包含数组数组的数组,而不是一个字符串数组。 You should be looping over the array values from the dictionary and adding the items from each one to your mutarr to make it an array of strings that you can sort. 您应该循环遍历字典中的数组值,并将每个项目中的项目添加到mutarr以使其成为可以排序的字符串数组。

If your NSDictionary values are arrays then you are trying to sort the arrays instead of the strings. 如果您的NSDictionary值是数组,那么您正在尝试对数组进行排序而不是字符串。 Try to create a for loop to iterate [self.firstTableView allValues] then add all values in that array to your main to sort array. 尝试创建一个for循环来迭代[self.firstTableView allValues],然后将该数组中的所有值添加到main以排序数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM