我有一个包含键@"Category"
的对象数组(字典)。我必须通过从该键开始的特定键对其进行排序。例如,如果objects[@"Category"]: A, B ,C ,D ,E ,F ,G , H etc.
中的值和用户选择“按C排序”,我需要通过[@"Category"]
到的对象重新排序根数组:C,D,E,F,G,H ,A,B - 或 - C,A,B,D,E,F,G,H。
我希望很清楚我的目标是什么。我试过了:
// sortedPosts2 = [self.objects sortedArrayUsingComparator:^(PFObject *object1, PFObject *object2) {
// return [object1[@"Category"] compare:object2[@"Category"] options:NSOrderedAscending];
// }];
// NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:category ascending:YES];
// sortedPosts2 = [self.objects sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];
[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationTop];
}
答案 0 :(得分:1)
我能想到的最简单的方法就是排序。然后,您可以手动调整数组比较值。这适用于Category
中任何大小的字符串。您可能需要更改大于标志或升序/降序回报,我总是与升序/降序混淆......
NSArray *array;
NSString *userSelectedValue = @"C";
array = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSString *category1 = [[(NSDictionary*)obj1 objectForKey:@"Category"] lowercaseString];
NSString *category2 = [[(NSDictionary*)obj2 objectForKey:@"Category"] lowercaseString];
//Now check if either category's value is less than the user selected value
NSComparisonResult result1 = [category1 compare:[userSelectedValue lowercaseString]];
NSComparisonResult result2 = [category2 compare:[userSelectedValue lowercaseString]];
if(result1 == result2)
{
return [category1 compare:category2];
}
else if(result1 > result2)
{
return NSOrderedDescending;
}
else
return NSOrderedAscending;
}];