Search code examples
objective-ciosxcode4nsmutablearraynsmutabledictionary

What is the Difference b/w addObject:dictionary and addObject:[dictionary copy] to an NSMutableArray?


I'm trying to set some values to my NSMutableDictionary inside a loop and assigning the dictionary values to an NSMutableArray each time like below,

for(int i=0;i<=lastObj;i++){
[mutableDict setValue:[valuesArray objectAtIndex:i] forKey:@"Name"];
[mutableDict setValue:[uniqueArray objectAtIndex:i] forKey:@"SSN"];
//......then
**[mutableArray addObject:mutableDict];**/*not working perfectly all values s replaced by final mutableDict values (duplicate values)*/

but

**[mutableArray addObject:[mutableDict copy]];**/* Working Correctly !!! */
}

inside loop in each iteration new values is assigned to mutableDictionary and whenever i say just addObject my mutableArray is getting all duplicate values but whenever i say addObject:[mutableDict copy], array is getting correct unique values without any duplicates, i don't know what the difference the compiler feels when i say copy, can anybody tell me the difference in this. Thanks in advance.


Solution

  • [mutableArray addObject:mutableDict];
    

    keeps on adding mutableDict to mutableArray. adding the object doesnt create a new memory location, it points to the same memory. so when u set the values of mutableDict, it gets reflected in all added objects as they refer to same memory location.

    copy creates a new memory location and adds the object removing the above scenario.

    to avoid this u can add

    for(int i=0;i<=lastObj;i++){
    NSMutableDictionary * mutableDict = [NSMutableDictionary new]; //create new memory location
    [mutableDict setValue:[valuesArray objectAtIndex:i] forKey:@"Name"];
    [mutableDict setValue:[uniqueArray objectAtIndex:i] forKey:@"SSN"];
    
    [mutableArray addObject:mutableDict];
    [mutableDict release]; //release 
    }
    

    hope this helps u. happy coding :)