我正在构建一个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]];
)后崩溃。
任何帮助将不胜感激,如果需要,我会很乐意添加更多的代码。
'customerArray'字符串中的元素是?如果是这样,比你得到的错误,因为你比较这些元素的'ID'属性,这是不存在的。删除描述符并使用'[customerArray sortUsingSelector:@selector(localizedStandardCompare :)]'直接比较元素 – Doc
@Doc你说得对,它们是字符串,但我完全忘了,认为它是原来的字典数组,早先创建。谢谢,那有效。如果你把这个作为答案,我会接受它。 – JustMe