Friday, September 18, 2015

Objective C copy and mutableCopy

In Objective C, there are mutable versions for basic data types as shown below.


Data TypeMutable
NSArrayNSMutableArray
NSSetNSMutableSet
NSDictionaryNSMutableDictionary
NSStringNSMutableString

The use of these mutable versions is, they are dynamic in nature. Means, we can add/edit and delete items from those mutable versions.


                         



For example, if we declared an array like this.

NSArray *fruits = [[NSArray alloc] initWithObjects:@"apple",@"orange",@"grape",nil];

That's it, we can't edit (insert, delete, add) this array at run time.

It won't work out if we need to play around with an array of elements at run time. If we need to edit the items in an array at run time, we need to go for the mutable one which is NSMutableArray.

NSMutableArray *mutableFruits = [NSMutableArray alloc] init];

After the above initialisation, the count of mutableFruits array is 0. Now, we can add elements to this array as shown below.

[mutableFruits addObject:@"grapes"];
[mutableFruits addObject:@"apples"];
[mutableFruits addObject:@"bananas"];
[mutableFruits addObject:@"oranges"];

We can remove elements as shown below.

[mutableFruits removeObjectAtIndex:1];
[mutableFruits removeAllObjects];

If you observe, it is very handy using mutable versions if the elements are dynamic at run time. Same applies for strings, sets and dictionaries.

Sometimes, we need to maintain both the versions like for example, I need basic fruits array across my application. But, at some point I need the mutable version of it to add or remove the items based on my functional requirement with out disturbing my basic array.

Here comes the concept of copy and mutableCopy. Let's see what copy does. 

NSArray *fruitsCopy = [fruits copy];

The above statement creates an exact copy of fruits array. That means, this copy returns the same NSArray, whose items we can't edit at run time.

Where as, 

NSMutableArray *fruitsMutableCopy = [fruits mutableCopy];

gives you the mutable version(NSMutableArray) of fruits array, whose content can be edited at run time.

Though the mutable versions are very useful, be careful while going for them as they occupy more memory than the normal ones until unless you specify exactly. So, go for them only you will have to edit their content at run time.

Thanks for reading this article. Hope you found it useful :)