NSCopying and NSMutableCopying protocol


NSCopying is an agreement with the object copy. If you want an object of a class to support a copy, you need to enable the class to implement the NSCopying protocol. There is only one NSCopying protocol declaration method – (ID) copyWithZone: (NSZone *) zone. When our class implements the NSCopying protocol, by calling the copy method of the class object, the copy method will call us to achieve – (ID) copyWithZone: (NSZone *) zone method to achieve copy function. The implementation code is as follows:

- (ID) copyWithZone: (NSZone *) zone{PersonModel *model [[[self class] allocWithZone:zone] = init]; model.firstName = self.firstName; model.lastName = self.lastName; / / undisclosed members of model-> _nickName = _nickName; return model;}

Description: In – (ID) copyWithZone: (NSZone *) zone method, the [self method must be returned by the class] method to call the allocWithZone: method. Because pointers may actually point to a subclass of PersonModel. In this case, by calling [self class], you can return the correct class type object.


The main difference between NSCopying and NSMutableCopying is whether the returned object is variable. A case study of NSArray framework in Foundation

NSArray *nameArray = "Jim" @[@ @ @ "Tom", "David"]; NSArray *copyArray = [nameArray copy]; NSMutableArray *mutableCopyArray = [nameArray mutableCopy]; [mutableCopyArray addObject:@ "Sam"];

When the NSArray object calls the copy method, the copy method calls – (ID) copyWithZone: (NSZone *) zone to get a copy of the object, but the resulting object is immutable. While the NSArray object calls the mutableCopy method, the mutableCopy method will call – (ID) mutableCopyWithZone: (NSZone *) zone to get the variable object.

So, if a custom class is different and immutable, want it to support the copy, you need to implement both the NSCopying and NSMutableCopying, in – (ID) copyWithZone: (NSZone * zone) returns an immutable object, in – (ID) mutableCopyWithZone: (NSZone * zone) returns the variable object.

When copying an object, it is necessary to note that the copy is performed with a shallow or deep copy. Deep copy of the object, the object will be copied to the underlying data. All collections that are provided in the Foundation framework are supplied by default. Take the above code as an example, when nameArray executes copy, get a new array object. But the store store new objects in the string and nameArray are the same string; if the execution is a deep copy, will perform the copy operation of all strings in nameArray, and then added to the new object.