0

Let's say I have an array of custom objects. The custom class looks like this

Person
-------
name
number

Now let's say I want to rearrange the array of these objects so that the objects are sorted by the number. How can this be done?

Georg Schölly
  • 124,188
  • 49
  • 220
  • 267
node ninja
  • 31,796
  • 59
  • 166
  • 254
  • 1
    Xcode is an IDE, it is not a programming language / library. – kennytm Sep 25 '10 at 10:23
  • possible duplicate of [How to sort an NSMutableArray with custom objects in it?](http://stackoverflow.com/questions/805547/how-to-sort-an-nsmutablearray-with-custom-objects-in-it) – Georg Schölly Feb 14 '11 at 12:14

1 Answers1

2

1) you have to implement following methods in your Person class

- (NSNumber *)numberForSorting {
  return self.number;
}

- (NSComparisonResult)compare:(Person *)person {
    return [[self numberForSorting] compare:[person numberForSorting]];
}


2) When a Person array is need to be sort you just call

a) in case of NSMutableArray

[peopleMutableArray sortUsingSelector:@selector(compare:)];

b) in case of NSArray

NSArray *sortedPeople = [peopleArray sortedArrayUsingSelector@selector(compare:)];
knuku
  • 6,082
  • 1
  • 35
  • 43
  • 1
    This is almost the correct answer. in the numberForSorting method you would return the NSNumber representation of self.number, not self.name. – node ninja Sep 26 '10 at 08:08