【问题标题】:NSSortDescriptor JSON feed UITableViewNSSortDescriptor JSON 提要 UITableView
【发布时间】:2023-03-23 07:34:01
【问题描述】:

我使用 rest kit 映射了我的 JSON 提要,并在我的 UITableView 中很好地显示。我想用NSSortDescriptor(我想?)对tableView的单元格进行排序,基于从名为'Temp'的json提要映射的'Double'

到目前为止,我的 NSSortDescriptor 代码是

NSSortDescriptor *tempSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"temp" ascending:YES];
weatherObjects = [weatherObjects sortedArrayUsingDescriptors:@[tempSortDescriptor]];

但不确定它是否正确,或者我是否需要将它放在我的 RKResponseDescriptor 之后或 tableView cellForRowAtIndexPath 中? (也许两者都没有?)

【问题讨论】:

    标签: ios objective-c iphone xcode uitableview


    【解决方案1】:

    在从 JSON 提要中检索到所有对象之后,在 UITableView 显示它之前进行排序。对数组进行排序后,将该数组用作cellForRowAtIndexPath 中的数据源并获取相应的对象。您可能需要将 weatherObjects 数组设为您的类的属性。

    @property (nonatomic) NSArray *weatherObjects;
    

    所以在cellForRowAtIndexPath:

    anObject = [self.weatherObjects objectAtIndex:indexPath.row];
    

    基于 OP cmets 的更新: 好的。所以假设你有两个对象。我将类型称为 MyMain。每一个都作为一个双变量,称为 temp。你有一个包含这两个对象的数组。

    MyMain *m1 = [MyMain new];
    m1.temp = 2.0;
    
    MyMain *m2 = [MyMain new];
    m2.temp = 1.0;
    
    NSArray *myObjects = @[m1, m2];
    
    NSArray *sortedArray = [myObjects sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        MyMain *o1 = obj1;
        MyMain *o2 = obj2;
        NSComparisonResult result = [[NSNumber numberWithDouble:o1.temp] compare:[NSNumber numberWithDouble:o2.temp]];
    
        return result;
    }];
    
    MyMain *s1 = sortedArray[0];
    MyMain *s2 = sortedArray[1];
    
    NSLog(@"First Object temp: %f and second object temp: %f", s1.temp, s2.temp);
    

    此打印对象的温度值为 1.0 第一和 2.0 秒。

    【讨论】:

    • 我有点困惑,我已经将weatherObjects 设为一个数组并设置了objectAtIndex:indexPath.ro.. 在我的JSON 请求之后我应该在viewdidload 中使用排序描述符吗? 'temp' 是一个 double,它在自己的类中称为 'main'。我想知道在我的 NSSortDescriptor initWithKey:@"temp" 中是否没有找到对其进行排序的值?
    • 如果 tableView 未加载,您可以使用viewDidLoad,但如果是,则需要重新加载 tableView。为了对您创建它的方式进行排序,它假定weatherObjects 有一个名为temp 的变量。如果不是这种情况,它将找不到它。您可以通过keyPath 而不是key 访问它。
    • temp 与weatherArray(weatherObjects) 中的一个对象在一起,但它在一个名为'main' 的对象中,然后在main 中它是'temp',我没有重新加载我的tableview 数据,但我还在没有让它排序。你能给我一些'keyPath'的示例代码吗?
    • 根据您的评论更新了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多