NSMutableArray of NSMutableDictionaries. Updating a value

Discussion in 'iOS Programming' started by estupefactika, Jul 1, 2009.

  1. estupefactika macrumors member

    Joined:
    Feb 16, 2009
    Location:
    Alcobendas (Madrid)
    #1
    Hi, I have a NSMutableArray of NSMutableDictionaries. How Could I update the value for a key of my array?
    My array is something like this:
    Code:
    (
            {
            name = "foo";
            surname = "woo";
        },
     {
            name = "foo2";
            surname = "woo2";
        }
    )
    
    I would like to update a value for key "name" for example:
    Code:
    for (int i=0; i<[feedArray count];i++) {
    		NSMutableDictionary *itemAtIndex = (NSMutableDictionary *)[feedArray objectAtIndex:i];
    [itemAtIndex setValue:@"David" forKey:@"name"];
    		
    		[feedArray insertObject:itemAtIndex atIndex:i];
    
    }
    
    But Im receiving the next error:
    Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '*** -[NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'

    It is any wrong? How Can I updated it? Thanks
     
  2. PhoneyDeveloper macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #2
    The runtime exception is telling you that you're trying to change a NSDictionary. IOW, what you think is a NSMutableDictionary is really a NSDictionary.

    Look at the code for where you create the array of dictionaries.

    Also, this line is wrong

    Code:
    	[feedArray insertObject:itemAtIndex atIndex:i];
    You should retrieve the dictionary at the desired index and update it. You don't have to insert it again.
     
  3. estupefactika thread starter macrumors member

    Joined:
    Feb 16, 2009
    Location:
    Alcobendas (Madrid)
    #3
    Ok. Thanks. Im creating my array in this way:
    Code:
    // save values to an item, then store that item into the array...
    item = [[NSMutableDictionary alloc] init];
    [item setObject:name forKey:@"name"];
    [item setObject:surname forKey:@"surname"];
    [feedArray addObject:[item copy]];
    [item release];
    
    Where feedArray is a NsMutableArray, item is a NsMutableDictionary and name and surname are NsMutableString. Is there any wrong there?
     
  4. PhoneyDeveloper macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #4
    Yes, copy returns an immutable copy. There's no reason to make a copy in this code that I can see. Just add item to the array.

    Code:
    [feedArray addObject:item];
    If you must make a copy use

    Code:
    [item mutableCopy];
     
  5. estupefactika thread starter macrumors member

    Joined:
    Feb 16, 2009
    Location:
    Alcobendas (Madrid)

Share This Page