1

I have an NSArray which contain objects. my Objects are like this :

@interface Personne : NSObject{

    int _id;
    NSString *name;
}

I have a Web services which returns to me persons by name. 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. 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. 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
Johnny Bones
  • 8,557
  • 6
  • 41
  • 108
samir
  • 4,411
  • 6
  • 47
  • 75
  • 1
    This answer is exactly what you're looking for: http://stackoverflow.com/questions/805547/how-to-sort-an-nsmutablearray-with-custom-objects-in-it Hope it helps! :) – Johannes Fahrenkrug Mar 15 '12 at 13:29

2 Answers2

2

I think you'd need an NSMutableArray, not NSArray. Also to sort use sortUsingSelector:

i.e. 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:)

check this - How to sort an NSMutableArray with custom objects in it?

Community
  • 1
  • 1
Srikar Appalaraju
  • 69,116
  • 53
  • 210
  • 260
2

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];
Oscar Gomez
  • 18,248
  • 12
  • 81
  • 116