NSDictionary allKeys订单

Nic*_*Roy 10 nsdictionary ios

我需要在UITableView中显示由API返回的NSDictionary的内容,尊重键的顺序.

我正在使用 :

- (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;
}
Run Code Online (Sandbox Code Playgroud)

但就像我一样self.data.allKeys,我正在失去我的钥匙的顺序.我无法按价值对它们进行排序,因为它与它们无关.

βha*_*avḯ 24

试试这个,

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

NSLog(@"%@",keys);
Run Code Online (Sandbox Code Playgroud)

现在根据排序的键获取值.

编辑

要按字母顺序对它们进行排序,试试这个,

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

NSLog(@"%@",keys);
Run Code Online (Sandbox Code Playgroud)


Nic*_*Roy 1

正如大家所说,我无法对出现在 NSDictionary 日志中的密钥进行排序,因为 NSDictionary 未排序。

我要求 API 中的人员返回一个数组:

0 => name : key 1
     value : value 1

1 => name : key 2
     value : value 2
Run Code Online (Sandbox Code Playgroud)

/ ------------------------------------------------- --------------------------- /

太糟糕了,没有这样使用的方法“sortedArrayUsingArray”:

NSArray * arrayOne = [@"key E", @"key A", @"key C"];

NSArray * arrayTwo = [@"key A", @"key B", @"key C", @"key D", @"key E", @"key F"];

NSArray * orderedArray = [arrayOne sortedArrayUsingArray: arrayTwo];
Run Code Online (Sandbox Code Playgroud)