iPhone Development:Basic introduction of NSDictionay in IOS

NSDictionary IOS



NSDictionary is an efficient way that allows user to associate data with respect to particular keys. Every dictionary has a key value pair associated with it.Whenever you used web-services now days, you are seeing that the response from server comes in JSON(Java Script object notation) form, which usually comprises of key value pair, virtually called as dictionary and in iPhone known as NSDictionary.

 Before we switch to our main purpose of this post i will tell you basics of NSDictionary

You can use dictionary as shown below

    NSDictionary *dict = @{@”Value”: @”Key”}; (in xcode 5)
Prior to Xcode 5 you can use it as
    NSDictionary *dict = [[NSDictionary alloc]initWithObjectsAndKeys:@”Value”,@”Key”,@”Value 2″,@”Key2″, nil];
Now you are familiar with NSDictionary creation let us undergo the technique of using it. As you know every NSDictionary has a key associated to its value.So we can get that value using its key.Below is the code chunk that shows how you can fetch value from an NSDictionary.

NSString *value = [dict vauleForKey:@”Key2″];
NSLog(@”Value == %@”,[dict valueForKey:@”Key2″]);

When you run your code at this moment, console will print value associated with key2, in our case it will print Value2.

You can check for the existence of particular key on your NSDictionary.For this you can use allKeys method of NSDictionary, which will return an array of keys associated with that particular dictionary. Then you can use containsObject method which will return you a bool value if key is present in your dictionary then containsObject will return YES otherwise NO. Below is the code that sums up our discussion for key existence.

    if ([[dict allKeys] containsObject:@”Key2″])
    {
        NSLog(@”Dictionary contains key key2″);
    }