November 27, 2009

Creating an Array of NSDictonary Objects

I had created an interface for the NSTableView class in InterfaceBuilder and needed a way to update the table with items. The easiest way seemed to be with an array of NSDictionary objects. But as I was not quite fimilar with the NSDictionary class I first had to look up how to create and fill one. Below is a base example I came up with.

// Aloc and Init Array
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:1];

// Setup keys
NSArray *keys = [NSArray arrayWithObjects:@"Name", @"Job", nil];

// Setup values
NSArray *values = [NSArray arrayWithObjects: @"Epic Box", @"running", nil];

// Add new NSDictionary with keys and values
[array addObject:[NSDictionary dictionaryWithObjects: values forKeys: keys]];

To get a value from a NSDictionary object you can do as follows...

//Using the array from the example above
NSInteger index = 0;
NSString *key = @"Name";

// Get value
NSString *result [[array objectAtIndex: index] objectForKey: key];

No comments: