views:

22

answers:

1

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?

+2  A: 

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:)];
NR4TR
This is almost the correct answer. in the numberForSorting method you would return the NSNumber representation of self.number, not self.name.
awakeFromNib
you're quite right, edited
NR4TR