为什么我不能将此NSArray转换为NSMutableArray来对其进行排序?

时间:2014-06-03 19:52:34

标签: ios objective-c cocoa-touch nsmutablearray nssortdescriptor

我将一些JSON数据序列化为字典。字典包含"状态"对象和一个字典数组(其中一个键是" time_dropped",我希望通过它对数组进行排序)。

然而,我得到一个例外,声称一个"变异方法[被]被发送到[一个]不可变对象"。这是相关的代码段。顺便说一句,我确实将pins声明为NSMutableArray

NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&localError];
NSString *status = [dataDictionary objectForKey:@"status"];
NSLog(@"status: %@", status);

if ([status isEqualToString:@"Okay"]) {
    self.pins = (NSMutableArray *) [dataDictionary objectForKey:@"pins"];

    NSSortDescriptor *timeDescriptor = [NSSortDescriptor
                                           sortDescriptorWithKey:@"time_dropped"
                                           ascending:YES selector:@selector(compare:)];

    NSSortDescriptor *titleDescriptor = [NSSortDescriptor
                                            sortDescriptorWithKey:@"title"
                                            ascending:YES selector:@selector(caseInsensitiveCompare:)];

    NSArray *descriptors = @[timeDescriptor, titleDescriptor];
    [self.pins sortUsingDescriptors:descriptors];

1 个答案:

答案 0 :(得分:2)

您不能通过强制转换将非可变数组转换为可变数组。您需要创建一个新的NSMutableArray:

NSMutableArray *array2 = [NSMutableArray arrayWithArray:array];

或者在你的情况下:

self.pins = [NSMutableArray 
                 arrayWithArray:(NSArray *)[dataDictionary objectForKey:@"pins"]];