[英]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. 编辑:关于复制 - 当您使用retain时,您只是增加对象的保留计数。 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.
单独表示它是一个保留计数为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) Alloc :当你需要进行内存分配时(你想要创建一个对象,你需要为它分配内存空间)
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).
它通过alloc和copy自动完成(复制意味着你需要该对象的副本)。 But you can also do it by using retain keyword.
但您也可以使用retain关键字来完成。
When retain count == 0, the object dealloc method will be called and will release all allocations made in that object. 当retain count == 0时,将调用object dealloc方法并释放该对象中的所有分配。
I hope it is clear enough. 我希望它足够清楚。 If you want more information : http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html
如果您需要更多信息,请访问: http : //developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.