Monday, 13 January 2014

difference between copy and retain in ios


copy: --> creates a new instance that's a copy of the receiver. It means that you'll have 2 different

retain: --> It is done on the created object, and it just increase the reference count.

NSObject *obj1 = [[NSObject alloc] init]; // obj1 has retain count 1

NSObject *obj2 = [obj1 retain];

// obj1 and obj2 both refer same object. now retain count = 2

// any change via obj1 will be seen by obj2 and vice versa, as they point same object

NSObject *obj3 = [obj1 copy];

// obj3 is a separate copy of the object. its retain count is 1 just like newly allocated object
// change via obj3 will not affect obj1 or obj2 and vice versa as they are separate objects


Example Code :--->

@implementation ABC

-(void) fun1
{
ObjectA * obj1 = [[ObjectA alloc] init]; // retainCount = +1
ObjectA * obj2 = obj1; // unchanged

// you have one instance of `ObjectA` with a retain count of +1
// both `obj1` and `obj2` point to the same single instance
}

-(void) fun2
{
ObjectA * obj1 = [[ObjectA alloc] init]; // retainCount = +1
ObjectA * obj2 = [obj1 retain]; // retainCount = +2

// you have one instance of `ObjectA` with a retain count of +2
// both `obj1` and `obj2` point to the same single instance
}

-(void) fun3
{
ObjectA * obj1 = [[ObjectA alloc] init]; // retainCount of `obj1` object = +1
ObjectA * obj2 = [obj1 copy]; // retainCount of `obj2` object = +1

// you have two instances of `ObjectA`, each with a retain count of +1
// `obj1` points to one instance and `obj2` point to the other
}

-(void) fun4
{
ObjectA * obj1 = [[ObjectA alloc] init]; // retainCount of `obj1` object = +1
ObjectA * obj2 = [obj1 mutableCopy]; // retainCount of `obj2` object = +1

// you have two instances of `ObjectA`, each with a retain count of +1
// `obj1` points to one instance
// `obj2` points to another instance, which is mutable copy of the `obj1` instance
}

@end

No comments:

Post a Comment