Reputation: 4551
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
Upvotes: 1
Views: 556
Reputation: 18488
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];
Upvotes: 2
Reputation: 73588
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?
Upvotes: 2