如何令自己所写的对象具有拷贝功能

.h
#import 

@interface Person : NSObject

@property (nonatomic, assign) NSInteger age;

@property (nonatomic, copy) NSString *name;

@end
.m
#import "Person.h"

@implementation Person

- (id)copyWithZone:(NSZone *)zone {
    
    Person *person = [[[self class] allocWithZone:zone] init];
    person.age = self.age;
    person.name = self.name;
    
    return person;
}

@end
调用
Person *person = [[Person alloc] init];
    person.age = 10;
    person.name = @"name";
    
    Person *person1 = [person copy];
    person1.age = 11;
    person1.name = @"name1";
    NSLog(@"person.age==%ld", person.age);//person.age==10
    NSLog(@"person.name==%@", person.name);//person.name==name
    NSLog(@"person1.age==%ld", person1.age);//person1.age==11
    NSLog(@"person1.name==%@", person1.name);//person1.name==name1
    

你可能感兴趣的:(如何令自己所写的对象具有拷贝功能)