Custom class implementation & lt; NSCopying & gt; Protocol, custom nscopying

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.