0 votes
asked in Objective C by (3.1k points)
Hi All

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

1 Answer

0 votes
answered by (4k 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];