iPhone - 按 CGRect 的 origin.x 对字典数组进行排序
我有一系列字典。 每个字典都是这样的
object, @"myObject",
[NSValue valueWithCGRect:myRect], @"rect",
nil
如何按 myRect.origin.x 对该数组进行排序?
我知道 Objective-C 有智能的方法来对字典数组进行排序。我的问题是,我想按 myRect 的 x 坐标进行排序,而 myRect 包含在 NSValue 中...有什么方法可以使用魔术命令来做到这一点吗?我知道你们都是魔术师! :D
谢谢。
I have an array of dictionaries.
Each dictionary is like this
object, @"myObject",
[NSValue valueWithCGRect:myRect], @"rect",
nil
How do I sort that array by myRect.origin.x ?
I know that objective-c has smart ways to sort arrays of dictionaries. My problem here is that I want to sort by the x coordinate of myRect and myRect is wrapped in a NSValue... any way to do that with a magic command? I know you guys are magicians! :D
thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最简洁的方法可能是使用像
sortUsingComparator:
或sortedArrayUsingComparator
这样的方法(取决于数组的可变性)并定义一个自定义比较器(一个带有两个参数并返回的块)一个NSComparisonResult
) 来解压你的矩形并比较它们的 x 坐标。编辑:好吧,既然其他人都提供了代码,这是我的:
The cleanest way is probably to use a method like
sortUsingComparator:
orsortedArrayUsingComparator
(depending on the mutability of the array) and define a custom comparator (a block taking two parameters and returning anNSComparisonResult
) that unpacks your rects and compare their x-coordinates.edit: Well, since everyone else is providing code, here's mine:
没有什么魔法,但它也不是免费的。 :) 您正在寻找
-[NSArray SortedArrayUsingComparator:]
。如果您的数组是NSMutableArray
那么您可以使用-[NSMutableArray sortUsingComparator:]
。比较器是一个返回 NSComparisonResult 并接受两个对象的块。这是
NSObjCRuntime.h
中的定义:该块应该获取对象,将它们转换为字典,将每个对象中的 NSValue 提取到矩形中,并返回比较 X 坐标字段的结果。
伪代码,假设有一个
NSMutableArray
:There's no magic, but it's not free, either. :) You're looking for
-[NSArray sortedArrayUsingComparator:]
. If your array is anNSMutableArray
then you can use-[NSMutableArray sortUsingComparator:]
.A comparator is a block which returns an
NSComparisonResult
and takes two objects. Here's the definition inNSObjCRuntime.h
:The block should take the objects, cast them to dictionaries, extract the NSValues from each back into rects and return the result of comparing the X coordinate fields.
Psuedocode, assuming an
NSMutableArray
:这应该可以做到(恐怕这不完全是一句台词):
This should do it (it's not quite a one-liner I'm afraid):