2016-07-29 77 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中的對象。

希望這可以解決您的問題。