Difference between retain and copy?

我是研究僧i 提交于 2019-11-29 22:04:35

问题


What exactly is the difference between retain and copy? what is its significance on reference counting?

I know that when an object is allocated using alloc/retain, reference count goes up by one. so how about using copy?

Another question relating to this is, the difference between using
@property(nonatomic, retain) and @property(nonatomic,copy)?


回答1:


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

copy -- create a new object




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/4827223/difference-between-retain-and-copy

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