I have read through many materials online which all explain when people should use "copy
" instead of "strong
".
"The copy attribute is an alternative to strong. Instead of taking ownership of the existing object, it creates a copy of whatever you assign to the property, then takes ownership of that. Only objects that conform to the NSCopying
protocol can use this attribute..."
And there are plenty of example codes showing when using "copy", the original value stays the same.
However, I'm new to Objective-C
. I really want to know how to use the newly assigned value. Where is the "new instance(copy)" with the "new value"? Do I need any additional methods to change the original value if I want to?
It will be great if someone can share an example for this part not the one proving the original value is not changed, which is everywhere.
Copy is useful when you do not want the value that you receive to get changed without you knowing. For example if you have a property that is an NSString and you rely on that string not changing once it is set then you need to use copy.
"The copy attribute is an alternative to strong. Instead of taking ownership of the existing object, it creates a copy of whatever you assign to the property, then takes ownership of that. Only objects that conform to the NSCopying protocol can use this attribute..."
assign -assign is the default and simply performs a variable assignment -assign is a property attribute that tells the compiler how to synthesize the property's setter implementation -I would use assign for C primitive properties and weak for weak references to Objective-C objects.
What the copy
attribute does behind the scenes is to create a setter like this:
- (void)setMyCopiedProperty:(MyClass *)newValue {
_myCopiedProperty = [newValue copy];
}
this means that whenever someone does something like this object.myCopiedProperty = someOtherValue;
, the someOtherValue
is sent a copy
message telling it to duplicate itself. The receiver gets then a new pointer (assuming copy
is correctly implemented), to which no-one excepting the receiver object has access to.
You can look at copy
as being exclusive in some kind of way:
Beware of the caveats, though:
NSArray
doesn't copy its objects, so you might end up thinking that a @property(copy) NSArray<MyClass *> *myProperty
is safe, however while the array itself is safe from being modified, the objects held by the array share the same reference. Same is true for any collection class (NSDictionary
, NSSet
, etc)copy
method does its job - i.e. creating a new object. This happens for all Cocoa/CocoaTouch classes that conform to NSCopying
, however for other classes this might or not be true, depending on implementation (myself I didn't saw yet a class that lies about its copy
method, however you never know)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With