Reputation: 247
I've a person object which has NSString properties firstname, lastname, birthday, and NSMutableDictionary of different phone numbers of that person.
I've to add different person objects in an array and sort those objects by their age, I've method to calculate their age but not sure how to link that calculated age with existing array of all person object and sort it.
Please help.
Upvotes: 0
Views: 114
Reputation: 57040
NSDateFormatter df = [NSDateFormatter new];
persons = [persons sortedArrayUsingComparator: ^(Person *p1, Person *p2) {
NSDate* d1 = [df dateFromString:p1.birthday];
NSDate* d2 = [df dateFromString:p2.birthday];
return [d1 compare:d2];
}];
Upvotes: 0
Reputation: 11834
Do I understand you correctly? Do you want to sort your array by the person's age?
Sorting can be rather easy by using the -sortedArrayUsingComparator:
method of NSArray. Let's say a person has a property called age which is of type NSInteger. We could sort the array like this:
// lets assume _persons_ is an array of Person objects ...
NSArray *sortedPersons = [persons sortedArrayUsingComparator: ^(Person *p1, Person *p2) {
if (p1.age > p2.age) {
return NSOrderedDescending;
}
if (p1.age < p2.age) {
return NSOrderedAscending;
}
return NSOrderedSame;
}];
Of course you could do any kind of comparison in the comparator. E.g. you could compare dates, strings, etc... The NSComparisonResult you return will move items inside the array to the correct position.
EDIT
The following might work in your particular situation:
NSArray *sortedPersons = [persons sortedArrayUsingComparator: ^(Person *p1, Person *p2) {
NSDate *date1 = [p1.birthday asDate];
NSDate *date2 = [p2.birthday asDate];
return [date1 compare:date2];
}];
Upvotes: 1
Reputation: 944
If you want to sort by particular property
(such as age
), use NSSortDesriptor
:
NSArray * people = ... //your array of Person objects
NSSortDescriptor * sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];
NSArray * sortedPeopleByAge = [people sortedArrayUsingDescriptors:@[sortDescriptor];
//sortedPeopleByAge are ... you know ... people sorted by age.
Hope this is what you meant.
Upvotes: 0