Nscopying
NSCopyingis a protocol related to the object copy. If you want a class object to support copying, you need to have the class implement the NSCopying protocol. NSCopyingthere is only one way to declare in an agreement - (id)copyWithZone:(NSZone *)zone . When our class implements the NSCopying protocol and invokes the method through the object of the class copy , the method calls the method copy we implement to - (id)copyWithZone:(NSZone *)zone implement the copy function. The implementation code looks like this:
- (id)copyWithZone:(NSZone *)zone{ PersonModel *model = [[[self class] allocWithZone:zone] init]; model.firstName = self.firstName; model.lastName = self.lastName; //未公开的成员 model->_nickName = _nickName; return model;}
Description: In a - (id)copyWithZone:(NSZone *)zone method, be sure to [self class] call the method through the object returned by the method allocWithZone: . Because the pointer might actually point to the PersonModel subclass. In this case, by calling [self class] , you can return the type object of the correct class.
Nsmutablecopying
NSCopyingNSMutableCopyingthe difference between the protocol and the main point is whether the returned object is a mutable type. Take the foundation framework NSArray as an example
NSArray *nameArray = @[@"Jim", @"Tom", @"David"];NSArray *copyArray = [nameArray copy];NSMutableArray *mutableCopyArray = [nameArray mutableCopy];[mutableCopyArray addObject:@"Sam"];
NSArraycopywhen an object invokes a method, the copy method calls - (id)copyWithZone:(NSZone *)zone to get a copy of the object, but the resulting object is still an immutable object. NSArraywhen the object calls mutableCopy the method, the mutableCopy method is called - (id)mutableCopyWithZone:(NSZone *)zone to get the Mutable object.
So, if a custom class has a mutable and immutable difference, and wants it to support the copy, it needs to implement both NSCopying and NSMutableCopying , in return, the immutable - (id)copyWithZone:(NSZone *)zone object, which - (id)mutableCopyWithZone:(NSZone *)zone returns the Mutable object.
When copying an object, it is important to note whether the copy performs a shallow copy or a deep copy. When a deep copy copies an object, the underlying data of the object is also copied. All the collections provided in the foundation framework, which are provided by default, are shallow copies. Take the code above as an example to nameArray copy get a new array object when executing. However, the string stored in the new object is the same string that is stored in it, and nameArray if a deep copy is executed, the nameArray operation is performed on all the strings in it and copy then added to the new object.
Wen/Huanglonghui (Jane book author)
Original link: HTTP://WWW.JIANSHU.COM/P/F84803356CBB
Copyright belongs to the author, please contact the author to obtain authorization, and Mark "book author".
Nscopying and Nsmutablecopying Protocol