简体   繁体   中英

What is the difference between alloc, retain and copy

这似乎是一个简单的问题,但我并不知道何时应该使用alloc,retain或copy。

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

Alloc : when you need to make memory allocations (You want to create an object, you need to allocate memory space for it)

Each object has a retain count which indicates the number of objects with an ownership interest in that object. It's automatically done with alloc and with copy (copy means you want a copy of that object). But you can also do it by using retain keyword.

When retain count == 0, the object dealloc method will be called and will release all allocations made in that object.

I hope it is clear enough. If you want more information : http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM