Wednesday, June 19, 2013

NSMutableDictionary setDictionary example in Objective C (iOS).


NSMutableDictionary setDictionary

Sets the contents of the receiving dictionary to entries in a given dictionary.

- (void)setDictionary:(NSDictionary *)otherDictionary

Parameters
otherDictionary
A dictionary containing the new entries.

Discussion of [NSMutableDictionary setDictionary]
All entries are removed from the receiving dictionary (with removeAllObjects), then each entry from otherDictionary added into the receiving dictionary.

NSMutableDictionary setDictionary example.
If you want to change the contents of the dictionary, you could just replace it with the new dictionary. In one line:

[dictionaryIvar setDictionary:[NSMutableDictionary dictionary]];

That has the same effect of doing a [dictionaryIvar removeAllObjects] (which also sends a release to all objects contained in it), followed by adding the objects from the new dictionary (in your case, empty).

Also, by doing this you don't have to worry about your ivar's ownership and memory management issues if all you need to do is 'reset' the dictionary...

Example of [NSMutableDictionary setDictionary].
[array replaceObjectAtIndex:i withObject:targetDict];
or

[tempDict setDictionary:targetDict]

NSMutableDictionary setDictionary example.
NSArray *columns = [fileBrowser tableColumns];
    int index, count = [columns count];
    for (index = 0; index < count; index++) {
NSTableColumn *column = [columns objectAtIndex:index];
[[column dataCell] setWraps:YES];
    }
.
.
NSMutableDictionary *rec = [[NSMutableDictionary alloc] init];
[rec setDictionary:[self createDicFromFile:fileName atPath:dirName withImageSize:size]];
if([rec count] == 0) continue;
[imageRecord addObject:rec];
[rec release];

End of NSMutableDictionary setDictionary example article.