简体   繁体   中英

Objective C - Can't change value in NSMutableArray

I can retrieve data I need from API, but then I can't change values of NSMutableArray. Here's the data I get from API:

{
favorites =     (
            {
        id = 766;
        imageUrl = "766.jpg";
        name = "Ground Beef 93% Lean 1LB PKG";
        price = "5.99";
        qty = 5;
        sale = "<null>";
        switch = 1;
    },
            {
        id = 3270;
        imageUrl = "3270.jpg";
        name = "Arnold Premium Italian Bread 20oz PKG";
        price = "5.39";
        qty = 5;
        sale = "<null>";
        switch = 1;
    },...
);
success = true;
}

I declare favorites property in the interface part :

@property (nonatomic, retain) NSMutableArray *favorites;

I store the data in NSMutableArray like this :

NSError *myError = nil;
NSMutableArray *response = [[NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError] mutableCopy];

Then I store favorite products in another NSMutableArray object :

NSString *success = [response valueForKey:@"success"];
if([success isEqualToString:@"true"]) {
    self.favorites = [response valueForKey:@"favorites"];
}

With this data I can display all images, prices, etc. in the table. Problem is when I want to update values in self.favorites mutable array:

[self.favorites[indexPath.row] setObject:@"0" forKey:@"switch"];

I get this error : -[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object . I even tried to add mutableCopy when assigning array to favorites :

self.favorites = [[response valueForKey:@"favorites"] mutableCopy];

but that did not work either.

You want NSJSONReadingMutableContainers , not NSJSONReadingMutableLeaves .

Using NSJSONReadingMutableLeaves gives you mutable strings and other mutable objects inside the containers. Not what you need here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM