Tuesday, May 7, 2013

NSDictionary dictionaryWithDictionary example ios


dictionaryWithDictionary:

Creates and returns a dictionary containing the keys and values from another given dictionary.
+ (id)dictionaryWithDictionary:(NSDictionary *)otherDictionary
Parameters of [NSDictionary dictionaryWithDictionary]
otherDictionary
A dictionary containing the keys and values with which to initialize the new dictionary.
Return Value
A new dictionary containing the keys and values found in otherDictionary.
Example of [NSDictionary dictionaryWithDictionary]
+ (NSMutableDictionary *)safeDictionaryWithDictionary:(NSDictionary *)dictionary
{
    return [NSMutableDictionary dictionaryWithDictionary:(dictionary ? dictionary : @{});
}
Example of [NSDictionary dictionaryWithDictionary]
@interface NSDictionary (JRAdditions)
- (NSDictionary *) dictionaryByReplacingNullsWithStrings;
@end

@implementation NSDictionary (JRAdditions)

- (NSDictionary *) dictionaryByReplacingNullsWithStrings {

   const NSMutableDictionary *replaced = [NSMutableDictionary dictionaryWithDictionary :self];
   const id nul = [NSNull null];
   const NSString *blank = @"";

   for(NSString *key in self) {
      const id object = [self objectForKey:key];
      if(object == nul) {
         //pointer comparison is way faster than -isKindOfClass:
         //since [NSNull null] is a singleton, they'll all point to the same
         //location in memory.
         [replaced setObject:blank 
                      forKey:key];
      }
   }
   return [NSDictionary dictionaryWithDictionary :replaced];
}

@end