我将一些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];
答案 0 :(得分:2)
您不能通过强制转换将非可变数组转换为可变数组。您需要创建一个新的NSMutableArray:
NSMutableArray *array2 = [NSMutableArray arrayWithArray:array];
或者在你的情况下:
self.pins = [NSMutableArray
arrayWithArray:(NSArray *)[dataDictionary objectForKey:@"pins"]];