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

后端 未结 9 1929
北恋
北恋 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 04:45

    if you use retain, it copy the pointer value from original one.retain also increment the reference count by one. but in case of copy, it duplicate the data referenced by the pointer and assign it to copy's instance variable.

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

    retain attribute is specified such that it can retain the another memory i.e it can be made to point to another address also copy First copies the address and then retains it.

    0 讨论(0)
  • Retaining and copying are two different things, the first is conceptually call-by-reference while the second is call-by-value.

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

    copy: creates a new instance that's a copy of the receiver. It means that you'll have 2 different

    retain: Increases the retainCount of the receiver. An object is removed from memory - (with dealloc), when retainCount is 0.

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

    The biggest difference is that if you use copy, the object you are copying must implement the NSCopying protocol (very easy to do). Not every object implements that, so you need to use care you know for sure what type you'll be operating against (or check for support of that protocol) when trying to call copy.

    The best rule of thumb to using copy I can think of, is to always set NSString properties to "copy" instead of retain. That way you get more accurate readings from the Leaks instrument if you mess up and forget to release a string an object is holding onto. Other uses of copy need to be more carefully thought out.

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

    Retaining an object means the retain count increases by one. This means the instance of the object will be kept in memory until it’s retain count drops to zero. The property will store a reference to this instance and will share the same instance with anyone else who retained it too. Copy means the object will be cloned with duplicate values. It is not shared with any one else.

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