开发者

How to sort an NSArray of objects by their class?

I have an NSArray of objects that all subclass with their different types from a more abstract class.

I would like to sort the array by the object's class type. For example:

NSArray with CLASSA CLASSB AND CLASS C subclassed from CLASSz

myA开发者_如何转开发rray = {C, B, A}

Sort myArray decending: {A, B, C}

I see sort descriptors and that seems like it's the right path but I am comparing isKindOfClass which is not a property so can not be used in the NSSortDescriptiors thing.

Thanks for any help.


Well, the biggest hurdle I see is that you're probably going to need a custom property on Class objects which you could use as the key of an NSSortDescriptor. Unfortunately, there's no real way to add methods/categories to Class objects.

So what I would probably do is use NSStringFromClass() to convert your Class objects into strings, then use an NSString category to add a custom comparator method (something like compareToClass:) that converts the string back to a Class, does the subclass determination, and then returns the appropriate ordering constant.

From there, you can use NSArray's sortedArrayUsingSelector: method to get them in order.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜