-2

I am serialising some JSON data into a dictionary. The dictionary contains a "status" object, and an array of dictionaries (one key of which is "time_dropped", by which I want to sort the array).

However, I get an exception claiming that a "mutating method [was] sent to [an] immutable object". Here's the relevant piece of code. I did declare pins as a NSMutableArray, by the way.

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];
jscs
  • 63,694
  • 13
  • 151
  • 195
Rory Byrne
  • 923
  • 1
  • 12
  • 22
  • Rather than apologize for the bad formatting, please just fix it, as rmaddy has kindly done for you. – jscs Jun 03 '14 at 19:55
  • or you could use the `NSArray` method `sortedArrayUsingDescriptors:`. – CrimsonChris Jun 03 '14 at 19:56
  • Just because you said the `pins` reference points to an `NSMutableArray` will NOT stop you from pointing it at WHATEVER you want. I could do this... `self.pins = (id)[[UIViewController alloc] init];` and the compiler won't do anything to stop me. – CrimsonChris Jun 03 '14 at 19:58
  • Note that if you need mutable arrays/dictionaries in a JSON representation, NSJSONSerialization has an option to provide that, so you don't need to make copies. – Hot Licks Jun 03 '14 at 20:37
  • @JoshCaswell, I tried to fix it, but couldn't figure out how. Relax. – Rory Byrne Jun 04 '14 at 08:11

1 Answers1

2

You can't just turn a non-mutable array to a mutable array by casting. You need to create a new NSMutableArray:

NSMutableArray *array2 = [NSMutableArray arrayWithArray:array];

Or in your case:

self.pins = [NSMutableArray 
                 arrayWithArray:(NSArray *)[dataDictionary objectForKey:@"pins"]];
Philippe Leybaert
  • 168,566
  • 31
  • 210
  • 223