ShurupuS
ShurupuS

Reputation: 2923

Exception "mutating method sent to immutable object"

I Had an exception in the line [array removeObjectsInArray:toRemove]; in the method below and can't understand what's wrong with it..

- (void) handleDearchForTerm:(NSString *)searchTerm
{
    NSMutableArray *sectionsToRemove = [[NSMutableArray alloc] init];
    [self resetSearch];
    for (NSString *key in _keys)
    {
        NSMutableArray *array = [_names valueForKey:key];
        NSMutableArray *toRemove = [[NSMutableArray alloc] init];
        for (NSString *name in array)
        {
            if ([name rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location == NSNotFound)
                [toRemove addObject:name];
        }
        if ([array count] == [toRemove count])
            [sectionsToRemove addObject:key];
        [array removeObjectsInArray:toRemove];
    }
    [_keys removeObjectsInArray:sectionsToRemove];
    [_table reloadData];
}

Upvotes: 0

Views: 4286

Answers (2)

Grzegorz Krukowski
Grzegorz Krukowski

Reputation: 19802

Change:

 NSMutableArray *array = [_names valueForKey:key];

To:

 NSMutableArray *array = [[NSMutableArray alloc] initWithArray:[_names valueForKey:key]];

Or:

 NSMutableArray *array = [[_names valueForKey:key] mutableCopy];

Upvotes: 1

ivoryxiong
ivoryxiong

Reputation: 63

Probably array is just instance of NSArray, but not NSMutableArray, you shall check _names setObject:forKeys:

Upvotes: 3

Related Questions