开发者

What is the difference between alloc, retain and copy

开发者 https://www.devze.com 2023-01-23 11:07 出处:网络
This might seem a simple question, but I don\'t really get the idea o开发者_StackOverflow中文版f when should I use alloc, retain or copy.Please go through this long tutorial on memory management. It m

This might seem a simple question, but I don't really get the idea o开发者_StackOverflow中文版f when should I use alloc, retain or 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

0

精彩评论

暂无评论...
验证码 换一张
取 消