【问题标题】:Sort NSMutableArray using NSSortDescriptor使用 NSSortDescriptor 对 NSMutableArray 进行排序
【发布时间】:2016-07-29 00:08:06
【问题描述】:

我正在构建一个 iOS 应用程序。我需要对 NSMutableArray 进行排序,所以我使用了 NSSortDescriptor。但是,当我运行我的应用程序时,不幸的是得到了Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSTaggedPointerString 0xa000000343730314> valueForUndefinedKey:]: this class is not key value coding-compliant for the key ID.'

这是我正在使用的代码:

customerArray = [[NSMutableArray alloc] initWithArray:[rootDict allKeys]];
NSSortDescriptor *numberSorter = [NSSortDescriptor sortDescriptorWithKey:@"ID" ascending:YES selector:@selector(localizedStandardCompare:)];

[customerArray sortUsingDescriptors:@[numberSorter]];

以前,当我使用customerArray = [[NSMutableArray alloc] initWithArray:[rootDict allKeys]]; 时,我没有任何问题。一旦我添加了其他两行,我就开始遇到问题。我使用断点检查了它崩溃的位置,发现它在尝试运行最后一行后崩溃([customerArray sortUsingDescriptors:@[numberSorter]];)。

任何帮助将不胜感激,如果需要,我很乐意添加更多代码。

【问题讨论】:

  • customerArray 中的元素是字符串吗?如果是这样,那么您会得到错误,因为您正在比较这些元素的 ID 属性,该属性不存在。去掉描述符,使用[customerArray sortUsingSelector:@selector(localizedStandardCompare:)]直接比较元素
  • @Doc 你是对的,它们是字符串,但我完全忘记了,以为这是我之前创建的原始字典数组。谢谢,那行得通。如果你把它作为答案,我会接受。

标签: ios objective-c nsmutablearray nssortdescriptor


【解决方案1】:

正如您的错误状态 valueForUndefinedKey 这意味着 NSMutableArray 内的对象,即您的情况下的 customerArray 没有名称为 ID 的键(未定义键)。

您需要检查 NSMutableArray 中的对象。

希望这能解决您的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-02
    • 2013-03-10
    • 1970-01-01
    • 2012-08-22
    • 1970-01-01
    相关资源
    最近更新 更多