snksnk
snksnk

Reputation: 1595

Sorting array of dictionaries starting from a specific value

I have an array of objects (dictionaries) which contain a key @"Category". I have to sort it by a specific key starting by that key. For example if the values in the objects[@"Category"]: A, B ,C ,D ,E ,F ,G , H etc. and the user selects "sort by C" I need to reorder the root array by the object which [@"Category"] to: C,D,E,F,G,H,A,B -or- C,A,B,D,E,F,G,H .

I hope it is clear what my goal is. I tried:

//    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];
}

Upvotes: 0

Views: 78

Answers (1)

Putz1103
Putz1103

Reputation: 6211

The easiest way I can think of would be a sorting block. Then you can do manual adjustments to the array compare values. This should work for any size string in Category. You may need to change around greater than signs or Ascending/Descending returns, I always get mixed up with ascending/descending...

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;
}];

Upvotes: 1

Related Questions