Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object

When running the below code, the [dict setValue:@"null" forKey:@"name"]; keeps crashing. I search on here and found other posts were caused by people not using NSMutableDictionary. However I am using this.

Why is it crashing on this line if name is null?

NSMutableArray *tempCustomers = [[NSMutableArray alloc] init];
for (NSMutableDictionary *dict in [[json objectForKey:@"data"] mutableCopy]) {
    if ([dict objectForKey:@"name"] == [NSNull null]) {
        [dict setValue:@"null" forKey:@"name"];
    }
    [tempCustomers addObject:dict];
}
like image 434
Bot Avatar asked Dec 04 '22 01:12

Bot


2 Answers

I ended up using this. I'm guessing this is what a deepMutableCopy is?

NSMutableArray *tempCustomers = [[NSMutableArray alloc] init];
for (NSMutableDictionary *dict in [[json objectForKey:@"data"] mutableCopy]) {
    if ([dict objectForKey:@"name"] == [NSNull null]) {
        NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
        tempDict = [dict mutableCopy];

        [tempDict setValue:@"null" forKey:@"name"];
        [tempCustomers addObject:tempDict];
    } else {
        [tempCustomers addObject:dict];
    }
}
like image 199
Bot Avatar answered Jan 21 '23 17:01

Bot


maybe mutableCopy is not "deepMutableCopy", i mean, you just enumerate mutable object but objects in this collection are not mutable (copy from my comment)

like image 34
BergP Avatar answered Jan 21 '23 16:01

BergP