Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between alloc, retain and copy

This might seem a simple question, but I don't really get the idea of when should I use alloc, retain or copy.

like image 679
TheAmateurProgrammer Avatar asked Nov 28 '22 23:11

TheAmateurProgrammer


1 Answers

Please go through this long tutorial on memory management. It may require some time to read whole, but it explains the basic things nicely.

EDIT : About copy - When you are using retain then you are just increasing the retain count of the object. But when you use copy, a separate copy (shallow copy) of the object is created. Separate means it is a different object with retain count 1.

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];

like image 112
taskinoor Avatar answered Dec 09 '22 16:12

taskinoor