【问题标题】:Sorting array of dictionaries starting from a specific value从特定值开始对字典数组进行排序
【发布时间】:2014-02-19 17:47:50
【问题描述】:

我有一个对象数组(字典),其中包含一个键 @"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];
}

【问题讨论】:

  • 您的代码中似乎没有处理所选排序项...
  • sortDescriptorWithKey:category 其中 category 是用户选择的字符串

标签: ios objective-c arrays sorting


【解决方案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;
}];

【讨论】:

    猜你喜欢
    • 2016-03-03
    • 2019-03-07
    • 1970-01-01
    • 2020-10-27
    • 2016-04-17
    • 1970-01-01
    • 2014-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多