如何使用另一个包含对象有序键的 NSArray 对对象的 NSArray 进行排序?
例如,如果我有一个对象:
@interface MyObject
{
__id;
__data;
}
并且我有一个此类对象的 NSArray:
id=4
data=Apple
id=5
data=Banana
id=6
data=Orange
我还有一个 ids 的 NSArray:
{"5", "4", "6"}
现在我想按 ids 对对象数组进行排序,使其符合第二个数组中的顺序,因此结果应该是:
id=5
data=Banana
id=4
data=Apple
id=6
data=Orange
可能吗(在 iPhone 的 ObjC 中)?最有效的方法是什么?
谢谢!
for example, if I have an object:
@interface MyObject
{
__id;
__data;
}
and I have an NSArray of such object:
id=4
data=Apple
id=5
data=Banana
id=6
data=Orange
I also have an NSArray of ids:
{"5", "4", "6"}
now I want to sort the array of objects by ids to be in the order in the second array, so the result should be:
id=5
data=Banana
id=4
data=Apple
id=6
data=Orange
Is it possible(in ObjC for iPhone)? What is the most efficient way?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 NSArray 类的
- (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr
函数。您应该编写自己的比较器块,该块将根据 ids 数组中 id 的位置返回排序 - 即,当 idA 距离数组开头比 idB 更远时,返回 NSOrderedAscending。
希望这有帮助。
You can use
- (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr
function of the NSArray class.You should write your own comparator block that will return ordering depending on the position of id in the ids array - ie return NSOrderedAscending when idA is further from the start of the array than idB.
Hope this helps.