简体   繁体   English

使用自定义对象对数组进行排序

[英]Sort array with custom objects

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". 我编写的类包含一个NSString本身,即“名称”。 So what i wanna do, is to sort the array, based on the name property the objects contain. 所以我想做的就是根据对象包含的name属性对数组进行排序。 I tried the simple: 我尝试了简单的方法:

[anArray sortedArrayUsingSelecter: 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? 所以我想我必须使我的对象能够响应caseInsensitiveCompare吗? Not quite sure how to write such a method, so any pointers would be lovely. 不太确定如何编写这样的方法,因此任何指针都将很可爱。

Thanks 谢谢

You can use the method sortedArrayUsingComparator : 您可以使用sortedArrayUsingComparator方法:

NSArray *sortedArray = [anArray sortedArrayUsingComparator:^(MyClass *a, MyClass *b) {
    return [a.name caseInsensitiveCompare:b.name];
}];

You can sortedArrayUsingComparator:(NSComparator)cmptr ( NSArray reference ) to sort the array. 您可以sortedArrayUsingComparator:(NSComparator)cmptrNSArray参考 )对数组进行排序。 For instance, if you want to sort by the name property, do the following (assuming your class is called Person ): 例如,如果要按name属性排序,请执行以下操作(假设您的类称为Person ):

NSArray *sortedArray = [anArray sortedArrayUsingComparator:^(id a, id b) {
    NSString *first = [(Person *)a name];
    NSString *second = [(Person *)b name];
    return [first caseInsensitiveCompare:second];
}];

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

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