Collections: NSDictionary


/ Published in: Objective C
Save to your folder(s)



Copy this code and paste it in your HTML
  1. // NSDictionary exists, but you can`t add/remove items to it once it`s initialised
  2. // NSMutableDictionary inherits from NSDictionary
  3. // More info: http://developer.apple.com/documentation/Cocoa/Conceptual/Collections/Collections.html
  4. NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
  5.  
  6. // This is another way to initialise the dictionary, remember to use nil at the end
  7. // nil is just another definition of NULL
  8. NSMutableDictionary *dictionary2 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"obj1",@"key1",@"obj2",@"key2",nil];
  9.  
  10. // Adding keys
  11. [dictionary setObject: @"my object" forKey:@"key"];
  12. [dictionary setObject: @"my object" forKey:@"key2"];
  13.  
  14. // Getting by a single key
  15. NSLog(@"%@", [dictionary objectForKey:@"key"]);
  16.  
  17. // Enumerating
  18. for (NSString *key in dictionary)
  19. NSLog(@"key: %@, value: %@", key,[dictionary objectForKey:key]);
  20.  
  21. // Lookups would be performed using enumeration, there is no IndexOf or equivalent.
  22.  
  23. // Deleting
  24. [dictionary removeObjectForKey:@"key"];
  25.  
  26. // Count comes from the base, NSDictionary
  27. NSLog(@"Dictionary count: %i", dictionary.count);

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.