IOS "[__NSCFArray removeObjectAtIndex:]: mutation method sent to an immutable object"

Error:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray removeObjectAtIndex:]: mutating method sent to immutable object'

The code:

.h

@property (nonatomic, strong) NSMutableArray *history;

.m

- (void)tableView:(UITableView *)tableView commitEditingStyle:           (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
    {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSString *de = [[self.history objectAtIndex:indexPath.row] objectForKey:@"des"];
        NSString *dest = [de stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *jsonURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://example.com/rm_history.php?user_id=%@&destinations=%@",self.uID,dest]];
    NSData *jsonData = [NSData dataWithContentsOfURL:jsonURL];
         [self.history removeObjectAtIndex:indexPath.row];
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil]
                   withRowAnimation:UITableViewRowAnimationFade];   
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {   
        NSLog(@"create");
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
    [self.tableView reloadData];
}

After setting a breakpoint to catch the error, it stops at this line:

[self.history removeObjectAtIndex:indexPath.row];

Any idea on what is causing the problem?

+4
source share
4 answers

The fact that you declare historya NSMutableArraydoes not mean that it can only be assigned to it NSMutableArray. You can set immutable NSArrayfor historyif you are not careful. For example, this will happen if you serialize NSMutableArray, say, in JSON, and then deserialize it back to NSMutableArray: you get instead NSArray.

, , history NSMutableArray, mutableCopy NSArray, :

self.history = [[dataDictionary objectForKey:@"ds_history"] mutableCopy];
+25

, NSUserDefaults .

, Mutable- NSUserDefaults, . .

NSMutableArray *storeArray = [[defaultDefects objectForKey:@"defaultStoreDefects"] mutableCopy];
0

* NSUserDefaults *

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

NSMutableArray *history;

[userDefaults setObject:histrory forKey:@"des"];
[userDefaults synchronize];

history = [[userDefaults objectForKey:@"des"] mutableCopy];
0

, self.history NSArray, .

:

self.history = [NSMutableArray arrayWithArray:[dataDictionary objectForKey:@"ds_history"]];
-1

Source: https://habr.com/ru/post/1531590/


All Articles