Copy Vs Mutable Copy in iOS


It's found very confusing for most of the folks, who is not having much experience in Objective-C.

Before starting I just to say: Just remember below lines-

1 - copy always creates an immutable copy means you can not modify the object.
2 - mutableCopy always creates a mutable copy means you can modify the object


Here onwards I try to explain copy and mutable copy with some examples:

copy:

NSArray *obj = [NSArray arrayWithObjects:@"1",@"2", nil];


NSArray *copyObj = [obj copy];

NSArray *mutableObj = [obj mutableCopy];

When you try to see the details of copyObj its clearly shows __NSArrayI which tells that you can not modify this object

Printing description of copyObjy:
<__nsarrayi 0x6080000238a0="">(
1,
2
)

Same way When you try to see the details of mutableObj its clearly shows __NSArrayM which tells that you can modify this object

Printing description of mutableObjy:
<__nsarraym 0x608000057970="">(
1,
2
)

As the copyObj is assigned to of type NSArray so it will not reflect any method from NSMUtableArray class. So you will end up with compile time error.

[copyO bj removeObjectAtIndex:0] //error: No visible @interface for 'NSArray' declares the selector 'removeObjectAtIndex:'

As the mutableObj is assigned to of type NSArray so it will not reflect any method from NSMUtableArray class. So you will end up with compile time error.

[mutableObj removeObjectAtIndex:1//error: No visible @interface for 'NSArray' declares the selector 'removeObjectAtIndex:'

mutableCopy:


NSMutableArray *obj = [NSMutableArray arrayWithObjects:@"1",@"2", nil];

NSMutableArray *copyObjy = [obj copy];
NSMutableArray *mutableObjy = [obj mutableCopy];

When you try to see the details of copyObjy its clearly shows __NSArrayI which tells that you can not modify this object

Printing description of copyObjy:
<__nsarrayi 0x6080000238a0="">(
1,
2
)

Same way When you try to see the details of mutableObjy its clearly shows __NSArrayM which tells that you can modify this object

Printing description of mutableObjy:
<__nsarraym 0x608000057970="">(
1,
2
)

Now [copyObjy removeObjectAtIndex:0]; will make crash as you are trying to modify immutable object (__NSArrayI).


Whereas [mutableObjy removeObjectAtIndex:1]; will work as it return the mutable object. remove the object from mutable copy will not modify source object.


So the conclusion is copied return immutable object, can not be modified and mutable object return from mutableCopy which can modify and it will not modify the source object.

Hope I tried to explain everything and make clear about copy and mutableCopy. 
Please do comment and give your valuable suggestions.

If you want to go through other swift topics please, check this link





Comments

Popular posts from this blog

How to Disable iOS/iPad App availability on Mac Store, Silicon?

Closures in Swift - Part 1