BlackCat
BlackCat

Reputation: 33

Change every NSArray within NSDictionary to Mutable

I am having problem with the following code, I need to do some modification on each array within a NSMutableDictionary. When I first added those array into the dictionary, they are "MutableArray", but when I try to do something with them, they become a "NSArray".

here is my code:

UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
    NSString *cellText = selectedCell.textLabel.text;
    NSLog(@"cell: %@", cellText);

    Boolean flag = false;
    NSMutableDictionary *myTempDict = [[NSMutableDictionary alloc] initWithDictionary:self.tableContents copyItems:YES];

    for (NSString *key in myTempDict) 
    {
        NSLog(@"1st for");
        for(NSString *myString in [myTempDict objectForKey:key])
        {
            NSLog(@"2nd for");
            if([myString isEqualToString:cellText])
            {
                if([[myTempDict objectForKey:key] isKindOfClass:[NSMutableArray class]])
                {
                    NSLog(@"mutable");
                }
                else if([[myTempDict objectForKey:key] isKindOfClass:[NSArray class]])
                {
                    NSLog(@"not mutable");
                }
                [[myTempDict objectForKey:key] removeObject:myString];
                break;
                NSLog(@"break1");
            }
            NSLog(@"2nd for end");
        }
        if(flag)
        {
            break;
            NSLog(@"break2");
        }
    }
    self.tableContents = myTempDict;
    [tableView reloadData];

now when I run it, it generate the following error:

on my viewdidLoad I created those Array to be NSMutableArray, but now its back to NSArray, why? and any idea on how to tackle this problem?

really need help on this.

Thanks

Upvotes: 1

Views: 639

Answers (1)

Josejulio
Josejulio

Reputation: 1295

Acording to the documentation of NSDictionary

The copyWithZone: method performs a shallow copy. If you have a collection of arbitrary depth, passing YES for the flag parameter will perform an immutable copy of the first level below the surface. If you pass NO the mutability of the first level is unaffected. In either case, the mutability of all deeper levels is unaffected.

Why don't you try:

NSMutableDictionary *myTempDict = [self.tableContents mutableCopy];

Upvotes: 3

Related Questions