简体   繁体   English

对包含自定义对象的NSArray进行排序

[英]Sort an NSArray which contain custom objects

I have an NSArray which contain objects. 我有一个包含对象的NSArray my Objects are like this : 我的对象是这样的:

@interface Personne : NSObject{

    int _id;
    NSString *name;
}

I have a Web services which returns to me persons by name. 我有一个Web服务,可以通过名字返回给我。 for example; 例如; when I click in the search bar and I put "a", the server returns to me all the persons where her name contains "a", I put the result in an NSArray . 当我点击搜索栏并输入“a”时,服务器将所有名称中包含“a”的人返回给我,我将结果放入NSArray Now I would like to sort my array and put the persons whose name begins with "a" in the beginning of my array and the others at the end. 现在我想对我的数组进行排序,并将名称以“a”开头的人放在我的数组的开头,将其他人放在最后。 How can I do this? 我怎样才能做到这一点?

Edit: For example I have the response of the server like this : 编辑:例如我有服务器的响应,如下所示:

marakech  
arabie  
malakit  
arsenal  
astonvilla

I would like to sort like this : 我想这样排序:

arabie 
arsenal 
astonvilla 
malakit

I think you'd need an NSMutableArray , not NSArray . 我想你需要一个NSMutableArray ,而不是NSArray Also to sort use sortUsingSelector: 还要排序使用sortUsingSelector:

ie first you can write a method for your Personne class - (NSComparisonResult)compare:(MyObj *)otherObj , then you could can sort the mutable array with sortUsingSelector:@selector(compare:) 即首先你可以为你的Personne类编写一个方法- (NSComparisonResult)compare:(MyObj *)otherObj ,然后你就可以使用sortUsingSelector:@selector(compare:)对可变数组进行sortUsingSelector:@selector(compare:)

check this - How to sort an NSMutableArray with custom objects in it? 检查一下 - 如何使用自定义对象对NSMutableArray进行排序?

You can use this method: 您可以使用此方法:

- (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr

which takes a comparator block, then you can put your sorting criteria in the block like this: 这需要一个比较器块,然后您可以将您的排序标准放在块中,如下所示:

mySortedArray = [myArrat sortedArrayUsingComparator: ^(id a, id b) {
    //criteria;
    return [a compare:b];

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

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