热门搜索 :
考研考公
您的当前位置:首页正文

OC语言day08-20自定义类型实现copy

来源:东饰资讯网

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 方法中 创建 一个副本对象 , 然后将当前对象的值 赋值 给副本对象即可
     
     */
    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 方法, \
    在该方法中 先调用父类创建副本设置值,然后再设置 子类特有的值;
    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.创建一个新的对象
    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];  // 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.创建副本
//    调用父类的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

Top