Skip to content

Instantly share code, notes, and snippets.

@Sunnyztj
Created January 21, 2014 06:14
Show Gist options
  • Save Sunnyztj/8535173 to your computer and use it in GitHub Desktop.
Save Sunnyztj/8535173 to your computer and use it in GitHub Desktop.
sort in objective c (Block)
NSArray* ary = [dict objectForKey:@"stores"];
NSArray* sortedArray = [[NSArray alloc] init];
sortedArray = [ary sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSString *first = [NSString stringWithFormat:@"%@", [obj1 objectForKey:@"distance"]];
NSString *second = [NSString stringWithFormat:@"%@", [obj2 objectForKey:@"distance"]];
NSString *comFirst = [first substringWithRange:NSMakeRange(first.length-2, 1)];
NSString *comSecond = [second substringWithRange:NSMakeRange(second.length-2, 1)];
NSString *firstfloat;
NSString *seconfloat;
if ([comFirst isEqualToString:@"k"]) {
firstfloat = [NSString stringWithFormat:@"%f",[[first substringWithRange:NSMakeRange(0, first.length-3)] floatValue] * 1000];
}
else {
firstfloat = [NSString stringWithFormat:@"%f",[[first substringWithRange:NSMakeRange(0, first.length-2)] floatValue]];
}
if ([comSecond isEqualToString:@"k"]) {
seconfloat = [NSString stringWithFormat:@"%f",[[second substringWithRange:NSMakeRange(0, second.length-3)] floatValue] * 1000];
}
else {
seconfloat = [NSString stringWithFormat:@"%f",[[second substringWithRange:NSMakeRange(0, second.length-2)] floatValue]];
}
if ([firstfloat intValue] > [seconfloat intValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
if ([firstfloat intValue] < [seconfloat intValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment