Sunday, December 16, 2012

How to Use Dictionaries in Xcode: Quick Guide

diccionario xcode apple ios apps1 350x350 Cómo Utilizar Diccionarios en Xcode: Guía Rápida

Dictionaries are one of the most important tools in Objective-C and, unfortunately, are a mystery to many developers, since it is difficult to understand how they work properly. So many of us use in place arrays, accessing them through their index, thus losing one of the most powerful tools that Apple makes available to perform complex tasks in a simple way.

Quick Guide: Using Dictionaries in Xcode

In this tutorial we will explore in a simple way using dictionaries in very few steps. What we do today is create a simple database of phone numbers of various contacts and access them.

The first thing we will do is declare the dictionary just as you would with an ordinary array:

NSMutableDictionary * miDiccionario = [[NSMutableDictionary alloc] init];

Once created you can add the data using the method deem appropriate setValue. To add a value we must use to add and a key, which is used as an index to access the data:

[MiDiccionario setValue: [NSNumber numberWithInt: 555666777] forKey: @ "John Appleseed"];

In this case the charge number (as an integer) 555 666 777 to contact John Appleseed. We can load any more information to populate the database:

[MiDiccionario setValue: [NSNumber numberWithInt: 555648234] forKey: @ "Steve Woz"];

[MiDiccionario setValue: [NSNumber numberWithInt: 555867453] forKey: @ "Scott Roberts"];

To access the data, simply have to use the method objectForKey passing as key contact name to search. The method will return the value. As in this case we want an integer, we force the value using intValue well as operator:

NSInteger phone = [[miDiccionario objectForKey: @ "Steve Woz"] intValue];

We must not forget to free the memory once we finish. This is done as in a regular array:

[MiDiccionario release];

As you can see, the Spanish system is very simple to use, allowing us to access data without any problem. I hope that, from now on, you feel encouraged to use it and, as always, any questions you have you can send it to us through the comments.

More info on our iOS Development section.

Share this article with your friends on Facebook, Google+, Twitter and Pinterest with the buttons you'll find at the beginning of it. Thank you!

iPadizate , best blog on the Apple iPad.



No comments:

Post a Comment