xcode 对 NSMutuableArray 进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6294164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 21:13:46  来源:igfitidea点击:

Sort a NSMutuableArray

xcodesortingnsmutablearray

提问by pithhelmet

I have a NSMutableArray that is loaded with a inforamtion from a dictionary...

我有一个 NSMutableArray,它加载了字典中的信息......

[self.data removeAllObjects];  
NSMutableDictionary *rows = [[NSMutableDictionary alloc] initWithDictionary:[acacheDB.myDataset getRowsForTable:@"sites"]];      
self.data = [[NSMutableArray alloc] initWithArray:[rows allValues]];      

There are two key value pairs in the rows dictionary.

行字典中有两个键值对。

I need to sort the self.data NSMutableArray in alphabetical order.

我需要按字母顺序对 self.data NSMutableArray 进行排序。

How is this accomplished??

这是怎么实现的??

thanks
tony

感谢
托尼

回答by Yannick Compernol

If the values are plain strings you can use the following to create a sorted array:

如果值是纯字符串,您可以使用以下内容创建一个排序数组:

NSArray *sorted = [values sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];

回答by Regexident

This should do:

这应该做:

[self.data removeAllObjects];
NSArray *values = [[acacheDB.myDataset getRowsForTable:@"sites"] allValues];
NSSortDescriptor *alphaDescriptor = [[NSSortDescriptor alloc] initWithKey:@"DCFProgramName" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)];
NSArray *sortedValues = [values sortedArrayUsingDescriptors:[NSMutableArray arrayWithObjects:alphaDescriptor, nil]];
[alphaDesc release];
[self.data addObjectsFromArray:sortedValues];
  1. There's no need to clear an NSMutableArrayif you're replacing it shortly afterwards.
  2. There's no need to create an additional NSMutableDictionary, if you're not modifying anything in it.
  3. There's no need to create an additional NSMutableArray, if you could just as well just add the values to the existing one.
  1. NSMutableArray如果您稍后要更换它,则无需清除。
  2. NSMutableDictionary如果您不修改其中的任何内容,则无需创建额外的。
  3. NSMutableArray如果您可以将值添加到现有的值,则无需创建额外的.

Also: There are some serious memory leaksin your code. (2x alloc + 0x release = 2x leak)

另外:您的代码中存在一些严重的内存泄漏(2x 分配 + 0x 释放 = 2x 泄漏)

Edit: updated code snippet to reflect OP's update on data structure.

编辑:更新代码片段以反映 OP 对数据结构的更新。