Thursday 19 December 2013

Copy vs Retain in Objective C

Hi all, in one of my previous posts, we have discussed about memory management in Objective C using retain message. Sending "retain" message to a object will give ownership of the object. Now, lets see what we have to do to get a copy of object instead of just getting ownership of the object.

We have a method called "copy" in Objective C root class "NSObject". Using this method we can we can create a copy of an existing instance. Following is the syntax to do that.

Object *obj2 = [obj1 copy];

Now obj2 is exact copy of obj1. Both are difference objects. Newly created object "obj2" will have a retain count of 1 irrespective of the retain count of obj1.

Now lets take an example. I took NSMutableArray to explain the difference. Don't worry, if you don't know about NSMutableArray. Its just a collection object which holds a bunch of objects. If a object can be copied then it should confirm to NSCopying protocol.

We will discuss about collections and protocols in our next tutorials. For now just take NSMutableArray can hold a collection of objects and we can add or remove objects from it.


    NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"First",@"Second", nil];
    NSMutableArray *copiedArray = [array mutableCopy];
    NSMutableArray *retainedArray = [array retain];
    
    [retainedArray addObject:@"Retained Third"];
    [copiedArray addObject:@"Copied Third"];
    
    NSLog(@"array = %@",array);
    NSLog(@"Retained Array = %@",retainedArray);
    NSLog(@"Copied Array = %@",copiedArray);


Now look at the above code. First list shows creating a NSMutableArray object(array) with NSString elements @"First" and @"Second"(In Objective C we represent strings in @"").  copiedArray is copied object of array and retainedArray is retained object of array.

In next code we have added @"Retained Third" object to retained array and @"Copied Third" to copied array. After that I am printing the array values in console. (NSLog is used to print your logs in console. It uses c format specifiers. Apart from those, we can use %@ to print an object.)

Now here is the out put in console :

2013-12-19 17:15:49.379 RetainVsCopy[2876:c07] array = (
    First,
    Second,
    "Retained Third"
)
2013-12-19 17:15:49.380 RetainVsCopy[2876:c07] Retained Array = (
    First,
    Second,
    "Retained Third"
)
2013-12-19 17:15:49.381 RetainVsCopy[2876:c07] Copied Array = (
    First,
    Second,
    "Copied Third"
)

See, both array and Retained Array are having same contents. This is because both are pointing to same  memory/instance/object. Where as contents of Copied Array are different. This is because copy created a separate instance.

I hope this explanation helped you in figuring out difference between copy and retain. Feel free to ask your questions.

You can get source code of this example from here Source Code

6 comments: