我正在努力尝试对字典数组进行排序。
我的字典有一些有用的值,如价格、受欢迎程度等。
有什么建议吗?
我正在努力尝试对字典数组进行排序。
我的字典有一些有用的值,如价格、受欢迎程度等。
有什么建议吗?
可以像这样使用NSSortDescriptor
..
NSSortDescriptor * descriptor = [[NSSortDescriptor alloc] initWithKey:@"interest" ascending:YES];
stories = [stories sortedArrayUsingDescriptors:@[descriptor]];
recent = [stories copy];
stories
是您想要排序的数组。 recent
是另一个可变数组,其中包含已排序的字典值。将@"interest"
更改为您要排序的键值。
祝一切顺利
[array sortUsingDescriptors:[NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"YOUR-KEY" ascending:YES], nil]];
我不想将它分成几行。对我来说,它已经足够简单了。你只需从父级遍历到所需的子属性。例如:
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"parent.child.child" ascending:YES];
更新,sortUsingDescriptors现在已经更名为sortedArrayUsingDescriptors。
所以,它就像:
items = [items sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
[NSArray sortedArrayUsingDescriptors]
和 [NSMutableArray sortUsingDescriptors]
。后者仍然存在,没有被替换掉。 - Dalzhimarray = [array sortedArrayUsingDescriptors:[NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"YOUR-KEY" ascending:YES], nil]];
记得将值赋给数组
编写一个排序函数,比较两个字典中的相关字段。一旦你有了这个版本,你就可以例如使用NSArray#sortedArrayUsingFunction:context:
来对你的数组进行排序。