Thursday, 22 October 2015

Know about NSArray and NSDictionary in iOS

Arrays are used to store collection of values of similar types.

Two types of arrays are there in Objective c:

i) NSArray - NSArray is a immutable i.e. we cannot add or remove values dynamically.

    NSArray *phonesArray = @[@"iPhone",@"Samsung",@"Sony",@"HTC"];

    NSLog(@"All Phones %@", phonesArray);

Here , phoneArray is the name of the object of class type NSArray.
We can define the NSArrays using literals -  @[]
NSLog (@"") is used to print the values in the console screen (Like printf in C language).

Console Screen

Arrays index starts from Zero. i.e In the above array :- iPhone has 0th index, Samsung has 1st index and so on .

To print object at second index in console we use :

  NSLog(@"Phone at index 2 is %@", phonesArray[2]);

Here, phonesArray[2] gives the object at 2nd index of the phonesArray

Object at Second index of the array

ii) NSMutableArray - NSMutableArrays are mutable i.e we can add or remove values from these array types dynamically.

     NSMutableArray *phonesMutableArray = [[NSMutableArray alloc]initWithObjects:@"iPhone",@"Samsung",@"Sony",@"HTC", nil];            

    // Intialization of NSMutableArray with Object name phonesMutableArray
    NSLog(@"Phones Mutable Array  :- %@", phonesMutableArray);        

    // Printing array to the console screen
     [phonesMutableArray addObject:@"Xolo"];                            

     // Adding object dynamically
     [phonesMutableArray insertObject:@"Mi" atIndex:2];           
     // Adding Object at a specified index
     [phonesMutableArray removeObjectAtIndex:1];                           
    // removing Object from a specified index.

    [phonesMutableArray count];                             
    // Count the number of values in the Array

Dictionaries are used to store key-value associations.

There are two types of Dictionaries :
i) NSDictionary - NSDictionaries are immutable i.e they cannot be changed at the run time .

    NSDictionary *valuesDict = @{@"Name":@"Saurabh",@"Email":@"",@"Phone":@"9988207247"};

    // valuesDict is the object of the NSDictionary which contains values in key-value pair .
    // Name is key and Saurabh is value.
    NSLog(@"Our first Dictionary is :- %@",valuesDict);                                 // Printing dictionary to console


ii) NSMutableDictionary NSMutableDictionary is mutable i.e they can be changed at the run time .

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

    [valuesMutableDict setObject:@"Saurabh" forKey:@"Name"];

    NSLog(@"Mutable Dictionary is %@",valuesMutableDict);       // Printing dictionary to console
    // valuesMutableDict is the object of the NSMutableDictionary
    // Name is key and Saurabh is value.

Thank you :) 

No comments:

Post a Comment