Difference between retain and copy in objective-c

0 votes
359 views
asked Oct 15, 2013 in Objective C by jonathan (3,105 points)
Hi All

   Whats the difference between retain and copy in objective-c?

1 Answer

0 votes
answered Oct 15, 2013 by kalpana (3,995 points)

retain — is done on the created object, it just increase the reference count.

copy — create a new object.


For example

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

// 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 *obj2 = [obj1 retain];   

// 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
NSObject *obj3 = [obj1 copy];

 

...