Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
C# to Objective C by example #7
-(void) dictionaryExample
{
// NSDictionary exists, but you can`t add/remove items to it once it`s initialised
// NSMutableDictionary inherits from NSDictionary
// More info: http://developer.apple.com/documentation/Cocoa/Conceptual/Collections/Collections.html
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
// This is another way to initialise the dictionary, remember to use nil at the end
// nil is just another definition of NULL
NSMutableDictionary *dictionary2 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"obj1",@"key1",@"obj2",@"key2",nil];
// Adding keys
[dictionary setObject: @"my object" forKey:@"key"];
[dictionary setObject: @"my object" forKey:@"key2"];
// Getting by a single key
NSLog(@"%@", [dictionary objectForKey:@"key"]);
// Enumerating
for (NSString *key in dictionary)
NSLog(@"key: %@, value: %@", key,[dictionary objectForKey:key]);
// Lookups would be performed using enumeration, there is no IndexOf or equivalent.
// Deleting
[dictionary removeObjectForKey:@"key"];
// Count comes from the base, NSDictionary
NSLog(@"Dictionary count: %i", [dictionary count]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.