//
// main.m
// 自定义类实现copy
#import <Foundation/Foundation.h>
#import "Person.h"
#import "Student.h"
int main(int argc, const char * argv[]) {
/*
1.以后想让自定义的对象能够被copy只需要遵守NSCopying协议
2.实现协议中的- (id)copyWithZone:(NSZone *)zone
3.在- (id)copyWithZone:(NSZone *)zone方法中创建一个副本对象, 然后将当前对象的值赋值给副本对象即可
*/
Person *p = [[Person alloc] init];
p.age = 30;
p.name = @"lnj";
NSLog(@"%@", p);
Person *p22 = [p copy];//p没有copy方法,
Person *p2 = [p mutableCopy];
NSLog(@"%@", p2);//name= lnj, age = 30
NSLog(@"%@", p22);//name = lnj, age = 30
p.age = 100;
p.name = @"ssss";
NSLog(@"%@", p2);//name= lnj, age = 30
NSLog(@"%@", p22);//name = lnj, age = 30
Student *stu = [[Student alloc] init];
stu.age = 30;
stu.height = 1.75;
stu.name = @"lnj";
NSLog(@"stu = %@", stu);
// 如果想让子类在copy的时候保留子类的属性, 那么必须重写copyWithZone方法, 在该方法中先调用父类创建副本设置值, 然后再设置子类特有的值
Student *stu2 = [stu copy];
NSLog(@"stu2 = %@", stu2);
return 0;
}
//
// Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject<NSCopying, NSMutableCopying> //才有copy方法,
@property (nonatomic, assign) int age;
@property (nonatomic, copy) NSString *name;
@end
//
// Person.m
#import "Person.h"
@implementation Person
- (id)copyWithZone:(NSZone *)zone //拷贝一个副本
{
// 1.创建一个新的对象
Person *p = [[[self class] allocWithZone:zone] init]; //class方法,获取这个对象对应的类。
// 2.设置当前对象的内容给新的对象,拷贝的对象和原来对象的内容要一样,
p.age = _age;
p.name = _name;
// 3.返回新的对象
return p;
}
- (id)mutableCopyWithZone:(NSZone *)zone
{
// 1.创建一个新的对象
Person *p = [[[self class] allocWithZone:zone] init];
// 2.设置当前对象的内容给新的对象
p.age = _age;
p.name = _name;
// 3.返回新的对象
return p;
}
- (NSString *)description
{
return [NSString stringWithFormat:@"name = %@, age = %i", _name, _age];
}
@end
//
// Student.h
//
#import "Person.h"
@interface Student : Person //子类继承父类,会继承父类的协议。
@property (nonatomic, assign) double height;
@end
//
// Student.m
#import "Student.h"
@implementation Student
- (id)copyWithZone:(NSZone *)zone
{
// 1.创建副本
// id obj = [[self class] allocWithZone:zone];
id obj = [super copyWithZone:zone];
// 2.设置数据给副本
// [obj setAge:[self age]];
// [obj setName:[self name]];
[obj setHeight:_height];
// 3.返回副本
return obj;
}
- (NSString *)description
{
return [NSString stringWithFormat:@"name = %@, age = %i, height = %f", [self name], [self age], _height];
}
@end