What is the difference between “copy” and “retain”?

后端 未结 9 1930
北恋
北恋 2020-12-13 04:10

What is the difference between copy and retain for NSString?

- (void)setString:(NSString*)newString
{
    string = [ne         


        
相关标签:
9条回答
  • 2020-12-13 05:04

    In a general setting, retaining an object will increase its retain count by one. This will help keep the object in memory and prevent it from being blown away. What this means is that if you only hold a retained version of it, you share that copy with whomever passed it to you.

    Copying an object, however you do it, should create another object with duplicate values. Think of this as a clone. You do NOT share the clone with whomever passed it to you.

    When dealing with NSStrings in particular, you may not be able to assume that whoever is giving you an NSString is truly giving you an NSString. Someone could be handing you a subclass (NSMutableString, in this case) which means that they could potentially modify the values under the covers. If your application depends on the value passed in, and someone changes it on you, you can run into trouble.

    0 讨论(0)
  • 2020-12-13 05:04

    Its an old post but here's my view on the question

    Retain increases the retain count of an object by 1 and takes ownership of an object.

    Whereas copy will copy the data present in the memory location and will assign it to the variable so in the case of copy you are first copying the data from a location assign it to the variable which increases the retain count.

    Just remember that retain works on reference and copy works on value

    0 讨论(0)
  • 2020-12-13 05:09

    retain : It is done on the created object, and it just increase the reference count.

    copy -- It creates a new object and when new object is created retain count will be 1.

    Hope This Help for U...:)

    0 讨论(0)
提交回复
热议问题