Reputation:
in Objective C - what is the difference between dictionaries and arrays? Are dictionaries used with key : value (where Key can be any object), and arrays are id : value (where id is an integer)?
thanks
Upvotes: 1
Views: 2004
Reputation: 1070
Array
In Objective-C, an array is a type of collection which can store object types. It can store any type of objects. Objects stored in an array are linked to their index number.
eg. if you create an array and insert the first object, it will be stored in "index 0" and, the index number will keep on increasing from 0,1,2....n
Use "NSMutableArray" to create an array that can be modified.
example,
NSMutableArray *array = [NSMutableArray alloc] init];
[array addObject:@"Tom"];
[array addObject:@"Cat"];
So, at index 0, you will have "Tom". And, at index 1, you will have "Cat".
Dictionary
In Objective-C, a dictionary is a type of collection that stores "key-value" pairs. The "key" is of type ID, so you can enter any object as key for a value.
Use "NSMutableDictionary" to create a dictionary that can be modified.
example,
NSMutableDictionary *dictionary = [NSMutableDictionary alloc] init];
[dictionary setObject:@"Tom" forkey:@"name"];
[dictionary setObject:@"Cat" forKey:@"animal"];
The key difference between array and dictionary is the sequence of the objects gets changed in a dictionary, while in an array the sequence of objects stored is SEQUENTIAL.
[EDIT]
Since there has been quite a discussion with regard to this answer, I will make it clear that the array does NOT get re-created as some comments say.
The size of array/dictionary gets dynamically increased to accomodate the new elements in the colletion.
Upvotes: 1