samedi 25 avril 2015

Sorting NSArray of NSDictionary...not completely working


So I have NSMutableArray of NSDictionary items. Each NSDictionary item has a key "name" that should be used to sort the array alphabetically. Except its "sorting" partially works. Its not sorting in exact alphabetical order. It's moving some of the dictionary in order, but leaves some out of order.

NSMutableArray *section1 = [champs lastObject];
NSArray *oldSection1 = [NSArray arrayWithArray:section1];
[section1 sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSDictionary *dictA = (NSDictionary *)obj1;
    NSDictionary *dictB = (NSDictionary *)obj2;

    NSString *champName1 = dictA[@"name"];
    NSString *champName2 = dictB[@"name"];
    return [champName1 compare:champName2];
}];
// Animation
for (NSDictionary *champInfo2 in section1) {
    if ([oldSection1 indexOfObject:champInfo2] != [section1 indexOfObject:champInfo2]) {
        [self.collectionView moveItemAtIndexPath:[NSIndexPath indexPathForItem:[oldSection1 indexOfObject:champInfo2] inSection:1] toIndexPath:[NSIndexPath indexPathForItem:[section1 indexOfObject:champInfo2] inSection:1]];
    }
}

I even tried this code

NSMutableArray *section1 = [champs lastObject];
NSArray *oldSection1 = [NSArray arrayWithArray:section1];
/*[section1 sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSDictionary *dictA = (NSDictionary *)obj1;
    NSDictionary *dictB = (NSDictionary *)obj2;

    NSString *champName1 = dictA[@"name"];
    NSString *champName2 = dictB[@"name"];
    return [champName1 compare:champName2];
}];*/
section1 = [[NSArray arrayWithArray:section1] sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]]].mutableCopy;
// Animation
for (NSDictionary *champInfo2 in section1) {
    if ([oldSection1 indexOfObject:champInfo2] != [section1 indexOfObject:champInfo2]) {
        [self.collectionView moveItemAtIndexPath:[NSIndexPath indexPathForItem:[oldSection1 indexOfObject:champInfo2] inSection:1] toIndexPath:[NSIndexPath indexPathForItem:[section1 indexOfObject:champInfo2] inSection:1]];
    }
}


Aucun commentaire:

Enregistrer un commentaire