【问题标题】:Sort an array using NSSortDescriptor without use of any key?使用 NSSortDescriptor 对数组进行排序而不使用任何键?
【发布时间】:2015-06-11 13:10:09
【问题描述】:

我有一个数组appd.arrOfDictAppProd,其中有一个键Price,它是一个字符串值。但我想按价格值对这个数组进行排序。所以我从 appd.arrOfDictAppProd 数组中获取 Price 键并将 Price 转换为 String 到 Int,然后制作一个没有任何键的 NSMutableArray newarray。我想在不使用任何 Key 的情况下使用 NSSortDescriptor 对它进行排序,因为在我的 newarray 中没有键。我的代码在这里:

for (int i = 0; i<appd.arrOfDictAppProd.count; i++) {
    NSString *price_Value = [[appd.arrOfDictAppProd objectAtIndex:indexPath.row] objectForKey:@"price"];
    int price_IntValue = [price_Value intValue];
    NSLog(@"int value of prices:%d",price_IntValue);

    NSNumber *num = [NSNumber  numberWithInteger:price_IntValue];
    NSLog(@"number-%@",num);
    [newarray addObject:num];

}
NSLog(@"price array:%@",newarray);

NSSortDescriptor *sortDescriptor;
sortDescriptor =[[NSSortDescriptor alloc] initWithKey:@"num"
                                                    ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray1;
sortedArray1 = [newarray sortedArrayUsingDescriptors:sortDescriptors];

当我运行我的程序时,在 newarray 我有 14 个值,但它们是相同的,即 3。

【问题讨论】:

  • 修复 for 循环。您一遍又一遍地获取相同的对象,这就是为什么 newArray 包含 14 个相同的值。
  • @rmaddy。你能告诉我如何修复for循环..plz帮助
  • indexPath.row 替换为i
  • 是的。我已经改变了值..现在我门阵列中的 14 个不同的值。@谢谢亲爱的。

标签: objective-c nsmutablearray nssortdescriptor


【解决方案1】:

可能我错过了重点,但听起来你把事情过度复杂化了。

NSArray *sortedArray = [appd.arrOfDictAppProd sortedArrayUsingDescriptors:
    @[
        [NSSortDescritptor sortDescriptorWithKey:@"price.intValue" ascending:YES]
    ]];

如果你想创建 newarray 无论如何——或者只是没有你的手动循环——然后去:

NSArray *newarray = [appd.arrOfDictAppProd valueForKeyPath:@"price.intValue"];

这里依赖的机制是键值编码。我还构建了 NSDictionaryNSArray 实现键值编码的特定方式。

-valueForKey:-valueForKeyPath:NSObject 提供。忽略特殊情况和回退,对象将通过将该属性的值作为对象返回来响应前者——除此之外,它会自动将内置数字类型转换为NSNumbers。后者将遍历对象层次结构,例如object.property1.property2 将请求object,然后从object 请求property1,然后从property1 请求property2

因此,您可以使用[stringObject valueForKey:@"intValue"] 访问stringObject 上的intValue 属性,然后让NSObject 将其打包成NSNumber

NSDictionary 有一个键值编码的实现,它将在字典中查找适当的值,除非它以 @ 为前缀,表示您想要关于字典的信息,而不是来自字典。因为您的键名是一个不以@ 开头的字符串,所以valueForKey: 最终会调用objectForKey:

因此,在字典数组上带有键 price.intValue 的排序描述符将向每个字典询问键 price 的值。字典将决定调用objectForKey:。它会得到一个字符串。它会在该字符串上调用intValue 并返回int。然后它将其包装到 NSNumber 中并比较所有字典的数字以确定排序。

NSArray 实现valueForKey:valueForKeyPath: 通过依次调用数组中每个项目的相应方法,然后返回包含所有这些结果的数组。所以你可以在一定程度上使用键值编码作为结果映射的一种方式。

【讨论】:

    【解决方案2】:

    因为newarray 只是NSNumbers 的一个(可变)数组,而NSNumber 实现了compare: 方法,所以可以调用

    [newarray sortArrayUsingComparator:@selector(compare:)];
    

    在for循环之后。您不需要排序描述符。

    【讨论】:

    • 为什么会被赞成?它不会有帮助。 OP 声明 newArray 一遍又一遍地包含相同的数字。更改排序将无济于事。该错误位于for 循环中。
    • @rmaddy.sorry for迟到回复。我现在需要帮助。
    • @rmaddy..你是对的。For循环中的错误,我问如何修复For循环。谢谢
    猜你喜欢
    • 2013-03-10
    • 2012-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多