views:

472

answers:

1

I have a plist. It has several dozen keys, each with NSMutableArray items:

...
<key>KeyName1</key>
<array>
    <string>String1</string>
    <string>String2</string>
    <string>String3</string>
</array>

<key>KeyName2</key>
<array>
    <string>String1</string>
    <string>String2</string>
    <string>String3</string>
</array>
...

I have need to remove "String1" for all keys. This is the function that I wrote:

void DeleteString(NSString *StringToDelete){
NSMutableDictionary *item=nil;  

item = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];   

for (id obj in item){
    NSString *removeThisObject=(NSString *)obj;
    NSArray *ObjectArray = [item objectForKey:obj];

    for (int i = 0; i< [ObjectArray count]; i++){
        NSString *objectString = [ObjectArray objectAtIndex:i];

        if([objectString isEqualToString:StringToDelete]){              
            NSLog(@"Remove This from Item Dictionary: %@",removeThisObject);

            [item removeObjectForKey:obj];          
        }
    }

}
[item writeToFile:filePath atomically: YES];
[item release]; 

}

I figured it'd be easier to remove just the entire key if it includes a value that I do not want, but the line: [item removeObjForKey:obj] throws a EXC_BAD_ACCESS.

This does not make sense to me because, as I understand it EXC_BAD_ACCESS means that a message was sent to a released method.

Here, 'item' isn't released is it? I have no error releasing 'item' just a few lines lower.

What is going on here? Is there a better way to remove "String1" from both Keys?

Thanks.

A: 

It's not because item is not released, but item is immutable.

Within a for-in loop, the iterator that's being traversed cannot be changed. If you do, the program will throw a mutated enumeration exception.

You could

  • gather all obj into a separate array, then -removeObjectsForKeys: at the end of the loop; or
  • iterate on a copy of keys of the items. Specifically, for (id obj in [item allKeys]).
KennyTM
I'm an idiot. I don't know why I didn't see that.
Andrew J. Freyer