简体   繁体   English

如何使用另一个包含对象的有序键的NSArray对对象的NSArray进行排序?

[英]How to sort an NSArray of objects using another NSArray which contains the ordered keys of objects?

for example, if I have an object: 例如,如果我有一个对象:

@interface MyObject
{
    __id;
    __data;
}

and I have an NSArray of such object: 我有这样的对象的NSArray:

id=4
data=Apple
id=5
data=Banana
id=6
data=Orange

I also have an NSArray of ids: 我也有一个ID的NSArray:

{"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对对象数组进行排序,使其在第二个数组中排序,因此结果应为:

id=5
data=Banana
id=4
data=Apple
id=6
data=Orange

Is it possible(in ObjC for iPhone)? 是否可以(在iPhone的ObjC中)? What is the most efficient way? 最有效的方法是什么?

Thanks! 谢谢!

You can use - (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr function of the NSArray class. 您可以使用- (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr函数。

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. 您应该编写自己的比较器块,该块将根据ids在ids数组中的位置返回排序-即,当idA比idB离数组的开头更远时,返回NSOrderedAscending。

Hope this helps. 希望这可以帮助。

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

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