使用自定义对象排序数组 [英] Sort array with custom objects
问题描述
我正在尝试对一个数组进行排序,这个数组充满了我编写的类中的对象。我编写的类包含一个NSString本身,作为名称。所以我想做的是根据对象包含的name属性对数组进行排序。我试过这么简单:
I'm trying to sort an array, filled with objects from a class i wrote. The class i wrote contains an NSString itself, as the "name". So what i wanna do, is to sort the array, based on the name property the objects contain. I tried the simple:
[anArray sortedArrayUsingSelecter: CaseInsensitiveCompare];
但是你可以猜到,它将caseInsensitiveCompare消息发送给对象本身,它不会回应那个。
But as you can guess, it sends the caseInsensitiveCompare message to the objects itself, and it won't respond to that one.
所以我猜我必须让我的对象能够响应caseInsensitiveCompare?不太确定如何编写这样的方法,所以任何指针都很可爱。
So i'm guessing i have to make my objects able to respond to the caseInsensitiveCompare? Not quite sure how to write such a method, so any pointers would be lovely.
谢谢
推荐答案
您可以使用方法 sortedArrayUsingComparator
:
NSArray *sortedArray = [anArray sortedArrayUsingComparator:^(MyClass *a, MyClass *b) {
return [a.name caseInsensitiveCompare:b.name];
}];
这篇关于使用自定义对象排序数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!