【发布时间】:2014-06-03 19:52:33
【问题描述】:
我正在将一些 JSON 数据序列化到字典中。字典包含一个“状态”对象和一个字典数组(其中一个键是“time_dropped”,我想通过它对数组进行排序)。
但是,我收到一个异常,声称“已将变异方法发送到 [an] 不可变对象”。这是相关的代码。顺便说一句,我确实将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];
【问题讨论】:
-
与其为错误的格式道歉,不如直接修复它,因为 rmaddy 已经为您做了。
-
或者你可以使用
NSArray方法sortedArrayUsingDescriptors:。 -
仅仅因为你说
pins引用指向NSMutableArray不会阻止你将它指向你想要的任何东西。我可以这样做...self.pins = (id)[[UIViewController alloc] init];并且编译器不会做任何事情来阻止我。 -
请注意,如果您需要 JSON 表示的可变数组/字典,NSJSONSerialization 可以提供该选项,因此您无需进行复制。
-
@JoshCaswell,我试图修复它,但不知道如何解决。放松。
标签: ios objective-c cocoa-touch nsmutablearray nssortdescriptor