How to use "copy" property in Objective-C? How to use "copy" property in Objective-C? ios ios

How to use "copy" property in Objective-C?


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:

  • the clients that set the property don't have access to the actual set value
  • the receiver doesn't have access to the original passed value.

Beware of the caveats, though:

  • a copied 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)
  • if the property matches to a custom class you need to make sure the 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)


Try this:

Model.h

@interface Model: NSObject@property (nonatomic,strong)NSString *firstName;@property (nonatomic,copy) NSString *lastName;@end

ViewController.m

-(void)viewWillAppear:(BOOL)animated{[super viewWillAppear:animated];Model *model = [[Model alloc]init];NSMutableString *str = [[NSMutableString alloc]initWithString:@"test"];model.firstName = str;model.lastName = str;NSLog(@"%@, %@", model.firstName, model.lastName);[str appendString:@"string"];NSLog(@"%@, %@ ", model.firstName, model.lastName);}Output : 1st Nslog = "test", "test"  2nd Nslog = "teststring", "test"


An instance of a class is a discrete copy. When you assign an instance of a class to be the value of a property with the copy attribute, a clone of that instance is made and that clone becomes the value of the property. There is no relationship between the original and its clone, so the property does not have access to the original instance at all. Changing an attribute of the property's value is changing the clone.

Note:

If you implement the setter for a copy property, it is your responsibility to ensure it actually creates a copy. As is true with all the attributes for a property, they only have meaning when the compiler is generating (synthesizing) the setter and/or getter for you.