2016-07-29 78 views
0

我正在构建一个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.'使用NSSortDescriptor排序NSMutableArray

这是我使用的代码:

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]];)后崩溃。

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

+2

'customerArray'字符串中的元素是?如果是这样,比你得到的错误,因为你比较这些元素的'ID'属性,这是不存在的。删除描述符并使用'[customerArray sortUsingSelector:@selector(localizedStandardCompare :)]'直接比较元素 – Doc

+0

@Doc你说得对,它们是字符串,但我完全忘了,认为它是原来的字典数组,早先创建。谢谢,那有效。如果你把这个作为答案,我会接受它。 – JustMe

回答

0

由于您的错误状态为valueForUndefinedKey这意味着NSMutableArray(即您的案例中的customerArray)内的对象没有名称为ID(未定义密钥)的密钥。

你需要检查你的NSMutableArray中的对象。

希望这可以解决您的问题。