Thursday, May 9, 2013

NSDictionary initWithDictionary example ios


initWithDictionary:

Initializes a newly allocated dictionary by placing in it the keys and values contained in another given dictionary.
- (id)initWithDictionary:(NSDictionary *)otherDictionary
Parameters
otherDictionary
A dictionary containing the keys and values with which to initialize the new dictionary.
Return Value of [NSDictionary initWithDictionary]
An initialized dictionary—which might be different than the original receiver—containing the keys and values found in otherDictionary.
Example of [NSDictionary initWithDictionary]
//anArray is a Array of Dictionary with 5 objs. 

//here we init with the first
NSMutableDictionary *anMutableDict = [[NSMutableDictionary alloc] initWithDictionary:[anArray objectAtIndex:0]];

... use of anMutableDict ...
//then want to clear the MutableDict and assign the other dicts that was in the array of dicts

for (int i=1;i<5;i++) {
    [anMutableDict removeAllObjects];
    [anMutableDict addEntriesFromDictionary:[anArray objectAtIndex:i]];
} 
Example of [NSDictionary initWithDictionary]
NSMutableString *foo = [NSMutableString stringWithString:@"a mutable object"];

NSMutableDictionary *dictionary1, *dictionary2;

dictionary1 = [NSMutableDictionary dictionaryWithObject:foo forKey:@"foo"];
dictionary2 = [[NSMutableDictionary alloc] initWithDictionary:dictionary1
               copyItems: YES];

[[dictionary1 objectForKey:@"foo"] appendString:@", mutated"];
[[dictionary2 objectForKey:@"foo"] appendString:@", mutated"];
Example of [NSDictionary initWithDictionary]
for(id tumblelogDictionary in tumblelogs){
    if ([tumblelogDictionary isKindOfClass:[NSDictionary class]]) {
        Tumblelog *tumblelog = [[Tumblelog alloc] initWithDictionary:tumblelogDictionary]; //line 589
        [userTumblelogs addObject:tumblelog];
        [tumblelog release];
    } else {
        // Appropriate error handling and / or logging.
    }
}