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 |
To print object at second index in console we use :
NSLog(@"Phone at index 2 is %@", phonesArray[2]);
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
// 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"};
// 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 :)
NSMutableDictionary *valuesMutableDict = [[NSMutableDictionary alloc] init];
[valuesMutableDict setObject:@"Saurabh" forKey:@"Name"];
NSLog(@"Mutable Dictionary is %@",valuesMutableDict); // Printing dictionary to console
Here[valuesMutableDict setObject:@"Saurabh" forKey:@"Name"];
NSLog(@"Mutable Dictionary is %@",valuesMutableDict); // Printing dictionary to console
// Name is key and Saurabh is value.
Comments
Post a Comment