pragma mark 自定義類型實現copy
pragma mark 概念
#pragma mark 代碼
import <Foundation/Foundation.h>
#pragma mark 類
#import "Person.h"
#import "Student.h"
#pragma mark main函數
int main(int argc, const char * argv[])
{
#pragma mark 自定義類型實現copy
#warning 1.
/**
1. 以后想讓 自定義的對象 能夠被copy, 只需要遵守 NSCopy協議
2. 實現協議中的 - (id)copyWithZone:(NSZone *)zone
3. 在 - (id)copyWithZone:(NSZone *)zone 方法中 創(chuàng)建 一個副本對象 , 然后將當前對象的值 賦值 給副本對象即可
*/
Person *p = [[Person alloc]init];
p.age = 24;
p.name = @"lyh";
NSLog(@"%@",p);
// [Person copyWithZone:] -[Person mutableCopyWithZone:]
// Person *p2 = [p copy];
Person *p2 = [p mutableCopy];
NSLog(@"%@",p2);
NSLog(@"----- 1. end -----");
#warning 2.
Student *stu = [[Student alloc]init];
stu.age = 24;
stu.name = @"lys";
stu.height = 1.72;
NSLog(@"stu = %@",stu);
// 如果想 讓 子類 在copy 的時候 保留子類的屬性,那么必須重寫 allocWithZone 方法, \
在該方法中 先調用父類創(chuàng)建副本設置值,然后再設置 子類特有的值鸳粉;
Student *stu2 = [stu copy];
NSLog(@"stu2 = %@",stu2);
return 0;
}
Person.h //人類
#import <Foundation/Foundation.h>
@interface Person : NSObject<NSCopying,NSMutableCopying>
@property (nonatomic,assign)int age;
@property (nonatomic,copy) NSString *name;
@end
Person.m
#import "Person.h"
@implementation Person
- (id)copyWithZone:(NSZone *)zone
{
// 1.創(chuàng)建一個新的對象
Person *p = [[[self class] allocWithZone:zone]init]; // class 獲取當前這個類
// 2.設置當前對象的內容 給 新的對象
p.age = _age;
p.name = _name;
// 3. 返回一個新的對象
return p;
}
- (id)mutableCopyWithZone:(NSZone *)zone
{
// 1.創(chuàng)建一個新的對象
Person *p = [[[self class] allocWithZone:zone]init]; // class 獲取當前這個類
// 2.設置當前對象的內容 給 新的對象
p.age = _age;
p.name = _name;
// 3. 返回一個新的對象
return p;
}
- (NSString *)description
{
return [NSString stringWithFormat:@"name = %@,age = %i",_name,_age];
}
@end
Student.h //學生類
#import "Student.h"
@interface Student : Person
@property (nonatomic,assign)double height;
@end
Person.m
#import "Student.h"
@implementation Student
- (id)copyWithZone:(NSZone *)zone
{
// 1.創(chuàng)建副本
// 調用父類的NSCopy方法
// id obj = [[super class] allocWithZone:@""];
//
id obj = [[self class]allocWithZone:zone];
// 2.設置數據給副本
[obj setAge:[self age]];
[obj setName:[self name]];
[obj setHeight:[self height]];
// 3. 返回副本
return obj;
}
- (NSString *)description
{
return [NSString stringWithFormat:@"name = %@,age = %i, height = %f",[self name],[self age],[self height]]; // [self xx] 調用get方法
}
@end