按键值对NSMutableArray进行排序会引发异常

时间:2013-06-26 17:21:32

标签: ios nsmutablearray

我正在尝试使用以下结构对NSMutableArray进行排序:

(
{
    Code = "390954-150";
    Size = "35";
},
{
    Code = 790540MSO;
    Size = "30";
}
)

我尝试根据代码值进行排序,NSMutableArray称为arrayProduct

//Sort array by Code
NSSortDescriptor *aSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Code" ascending:YES];
[arrayProduct sortUsingDescriptors:[NSArray arrayWithObject:aSortDescriptor]];
//

但是上面的代码抛出了以下异常:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray replaceObjectAtIndex:withObject:]: mutating method sent to immutable object'

1 个答案:

答案 0 :(得分:2)

您的arrayProduct看起来像NSArray

尝试将其转换为NSMutableArray和:

NSMutableArray *mutableProducts = [NSMutableArray arrayWithArray:arrayProduct];
[mutableProducts sortUsingDescriptors:[NSArray arrayWithObject:aSortDescriptor]];