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?
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?
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:)];