Reputation: 59
Have a little Problem and can´t find a working solution :(
I have a NSMutableArray like:
{
Entfernung = 129521;
"Event_DATE" = "2014-03-23";
"Event_ID" = 1;
"Event_KAT" = 1;
"Event_NAME" = achtzehn;
},
{
Entfernung = 112143;
"Event_DATE" = "2014-03-24";
"Event_ID" = 2;
"Event_KAT" = 2;
"Event_NAME" = neunzehn;
}
How can i sort this Array with the object "Entfernung"?
Thx 4 help! Gerhard
Upvotes: 0
Views: 43
Reputation: 52602
Give a man a fish, and he can eat today. Tell him how to fish, and he has to do the work himself for the rest of his life...
In Xcode, look at the help menu. In the help menu, you find an item "Documentation and API reference". There you type in "NSMutableArray", then you search for "sort". Which gives you five methods:
– sortUsingDescriptors:
– sortUsingComparator:
– sortWithOptions:usingComparator:
– sortUsingFunction:context:
– sortUsingSelector:
You can click on each one and read the description. The most straightforward to use is sortUsingComparator: which comes with a nice bit of sample code that you adapt for your purposes.
Upvotes: 0
Reputation: 668
Try something like this;
NSArray *stuff = .... //your array here;
NSSortDescriptor *sorter = [NSSortDescriptor sortDescriptorWithKey:@"Entfernung" ascending:YES comparator:^NSComparisonResult(id obj1, id obj2) {
//depending on the number stored in the string, you might need the floatValue or doubleValue instead
NSNumber *num1 = @([(NSString*)obj1 integerValue]);
NSNumber *num2 = @([(NSString*)obj2 integerValue]);
return [num1 compare:num2];
}];
NSArray *sortedStuff = [[stuff sortedArrayUsingDescriptors:@[sorter]];
Upvotes: 1
Reputation: 33
The easiest I'd say would be to define a compare method on Entfernung
class and then use - (void)sortUsingSelector:(SEL)comparator
If you already have a function which accepts two objects (say your NSDictionary
object) then I'd do the sort like this - (void)sortUsingFunction:(NSInteger (*)(id, id, void *))compare context:(void *)context
Upvotes: 0