2

我有一个从 JSON 查询创建的 NSMutableDictionary,在浏览器中运行 json 查询会根据我的需要按字母顺序排列输出,并使用 NSLOG 以正确的顺序显示它来验证这一点。但是,当我填充 UITableView 单元格时,顺序完全不同,但我希望保留原始顺序。

我知道字典不是为了排序而设计的,我可以映射到一个新的排序数组,但是如果我这样做(如果这是实现这一目标的正确方法?)目前还不清楚如何为详细视图处理正确的键和索引. 有什么想法吗?谢谢。

创建 JSON 数据和创建表格单元格的代码如下:

- (void) makeData {
    //Define dictionary
    fullDictionary = [[NSMutableDictionary alloc] init];

    //parse JSON data from a URL into an NSArray
    NSString *urlString = [NSString stringWithFormat:@"http://<JSON feed goes here>"];
    NSURL *url = [NSURL URLWithString:urlString];
    NSData *data = [NSData dataWithContentsOfURL:url];
    NSError *error;
    fullDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    // cell data - extracting the appropriate values by object rows
    cell.textLabel.text = [[[fullDictionary allValues] valueForKeyPath:@"strTerm"] objectAtIndex:indexPath.row];

    return cell;
}
4

1 回答 1

1

从您的代码来看,您似乎知道如何从字典中获取适当的数组,因为您显然是在使用数组来设置cell.textLabel. 因此,对该代码进行逆向工程,看起来未排序的数组由以下因素决定:

NSArray *originalArray = [[fullDictionary allValues] valueForKeyPath:@"strTerm"];

现在您只需要对该数组进行排序。如果它是一个简单的字符串数组,你可以做一些简单的事情:

NSArray *sortedArray = [originalArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

如果您正在处理更复杂的字典条目数组或类似的东西,排序方法的排列可以让您很好地控制。请参阅此处了解更复杂的排序方法,作为对 JSON 结果进行排序的一种方式:Filtering UITableView from XML source。这是一个与您不同的问题,但也许它让您了解您可以使用sortedArrayUsingComparator.

于 2012-11-29T16:34:52.250 回答