NSArray, NSDictionary and retrieving objects in Xcode (iOS)

This is a very sketchy post but all is explained in the code example, which can be placed inside any ViewController.m file you choose to create.

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
   
    NSArray *numbersEnglish = [[NSArray alloc] initWithObjects:@"One", @"Two", @"Three", @"Four", nil];
    NSArray *numbersFrench = [[NSArray alloc] initWithObjects:@"Un", @"Deux", @"Trois", @"Quatre", nil];
    NSArray *numbersItalian = [[NSArray alloc] initWithObjects:@"Uno", @"Due", @"Tre", @"Quattro", nil];
   
    // We've now created the arrays (containing NSStrings) that we'll be using in the dictionary
   
    NSDictionary *numberDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:numbersEnglish, @"English", numbersFrench, @"French", numbersItalian, @"Italian", nil];
 
    // Now the NSDictionary has been created and our NSArrays assigned to keys at the same time
   
    NSLog(@"Entire dictionary: %@", numberDictionary);
   
    // Now we've displayed the entire dictionary in the console.
   
    NSLog(@"French Numbers (accessed using objectForKey): %@", [numberDictionary objectForKey:@"French"]);
   
    // The console has now displayed the array of NSStrings linked to the French key
   
    NSLog(@"Second Italian Number (accessed by nesting an objectForKey inside an objectAtIndex call): %@", [[numberDictionary objectForKey:@"Italian"] objectAtIndex:1]);
   
    // Finally we have retrieved a single NSString from inside the NSArray for the Italian key
   
}

One of the reasons for writing this post was to provide the method by which we retrieve an NSArray item from within an NSDictionary using objectForKey: and ObjectAtIndex: in combination.


Endorse on Coderwall

Comments

Post a Comment