Difference between retain and copy?

岁酱吖の 提交于 2019-11-30 15:38:15

retain -- is done on the created object, it just increase the reference count.

copy -- create a new object

Jiraheta

Answering your question to the best of my knowledge. First, What exactly is the difference between retain and copy? what is its significance on reference counting?

retain - "Specifies that retain should be invoked on the object upon assignment. ... The previous value is sent a release message." So you can imagine assigning an NSString instance (which is an object and which you probably want to retain). So the retain count goes up by 1.

copy - "Specifies that a copy of the object should be used for assignment. ... The previous value is sent a release message." Basically same as retain, but sending -copy rather than -retain. if i remember correctly the count will go up by 1 too.

ok, now going into more detail.

Property attributes are special keywords to tell compiler how to generate the getters and setters. Here you specify two property attributes: nonatomic, which tells the compiler not to worry about multithreading, and retain, which tells the compiler to retain the passed-in variable before setting the instance variable.

In other situations, you might want to use the “assign” property attribute instead of retain, which tells the compiler NOT! to retain the passed-in variable. Or perhaps the “copy” property attribute, which makes a copy of the passed-in variable before setting.

I hope that helps. I found another post in here that might help you too.

Objective C - Assign, Copy, Retain

Cheers! Jose

Generally speaking, copy creates a new object which has the same value with the original object, and sets the reference count of the new created object to 1 (By the way, reference count of the original object is not affected).

However, copy is equivalent to retain for immutable object, which JUST increate the reference count of the original object by 1.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!