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.
eg:

    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.
eg:



     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 .
eg: 


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

Here
    // 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

NSDictionary






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

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

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

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


Thank you :) 
    

Comments

Popular Posts