Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDictionary allKeys order

I need to display in a UITableView the content of a NSDictionary returned by an API, respecting the order of the keys.

I'm using :

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        NSString *key = self.data.allKeys[indexPath.section];
        NSArray *list = self.data[key];
        id data = list[indexPath.row];

        PSSearchCell *cell = [PSSearchCell newCellOrReuse:tableView];

        cell.model = data;

        return cell;
}

but as I do self.data.allKeys, I'm loosing the order of my keys. I can't sort them by value as it doesn't concern them.

like image 368
Nicolas Roy Avatar asked Jul 19 '13 11:07

Nicolas Roy


1 Answers

Try this,

NSArray *keys = [myDictionary allKeys];
keys = [keys sortedArrayUsingComparator:^(id a, id b) {
    return [a compare:b options:NSNumericSearch];
}];

NSLog(@"%@",keys);

Now fetch values based on the key sorted.

EDIT

To sort them in alphabetical order try this,

NSArray *keys = [myDictionary allKeys];
keys = [[keys mutableCopy] sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

NSLog(@"%@",keys);
like image 145
βhargavḯ Avatar answered Oct 22 '22 08:10

βhargavḯ