简体   繁体   中英

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:

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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