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)?
retain -- is done on the created object, it just increase the reference count.
copy -- create a new object
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.
来源:https://stackoverflow.com/questions/4827223/difference-between-retain-and-copy