Custom class implementation <NSCopying> protocol, custom nscopying
Objective: To customize a Person class and implement copy.
First, define a Person class. Because it is a custom class, to support the copy method, you need to implement the <NSCopying> protocol.
@interface Person : NSObject<NSCopying>@property (nonatomic, retain)NSString * name;@property (nonatomic, retain)NSString * sex;- (void)setName:(NSString *)name sex:(NSString *)sex;@end
<NSCopying> the Protocol has a-(id) copyWithZone :( NSZone *) zone method, which must be implemented in the. m file of Person.
@ Implementation Person-(id) copyWithZone :( NSZone *) zone {id p = [[self class] allocWithZone: zone] init]; <span style = "white-space: pre "> // considering that Person may have child classes, id is used to represent the type [p setName: _ name sex: _ sex]; // you can specify the instance variable of the replication object, otherwise, return p;}-(void) setName :( NSString *) name sex :( NSString *) sex {_ name = name; _ sex = sex;} @ end
Test in main. m file
Person * p1 = [[Person alloc] init]; // create the p1 object [p1 setName: @ "Michael" sex: @ "male"]; // assign the Person * p2 = [p1 copy] To the p1 instance variable; // copy a new object p2 NSLog FROM p1 (@ "p2.name = % @, p2.sex = % @", p2.name, p2.sex); // print p2 name and sex p2.name = @ ""; // change p2 name NSLog (@ "p2.name = % @", p2.name ); NSLog (@ "p1.name = % @", p1.name); // print the name of p1 again to verify whether the name of p1 has changed
The following is the result:
21:27:59. 466 CopyTest [2053: 303] p2.name = Zhang San, p2.sex = male 21:27:59. 468 CopyTest [2053: 303] p2.name = Li Si 21:27:59. 468 CopyTest [2053: 303] p1.name = James
It can be seen that changing the p2 name does not affect the p1 name.