136,自定义Copy类

来源:互联网 发布:centos minimal 桌面 编辑:程序博客网 时间:2024/06/05 08:57

#import <Foundation/Foundation.h>


@interface Person :NSObject<NSCopying,NSMutableCopying>


@property(nonatomic,copy)NSString *name;

@property(nonatomic,assign)int age;


@end


@implementation Person


- (id)copyWithZone:(nullableNSZone *)zone{

    //1,创建对象

    Person *person = [[selfclass] allocWithZone:zone];

    //2,赋值

    person.name = _name;

    person.age = _age;

    

    return person;

}


- (id)mutableCopyWithZone:(nullableNSZone *)zone{

    //1,创建对象

    Person *person = [[selfclass] allocWithZone:zone];

    //2,赋值

    person.name = _name;

    person.age = _age;

    

    return person;

}


-(NSString *)description{

    return [NSStringstringWithFormat:@"name = %@,age = %i",_name,_age];

}


@end


@interface Student : Person


@property(nonatomic,assign)double weight;


@end


@implementation Student


-(id)copyWithZone:(NSZone *)zone{

    id obj = [supercopyWithZone:zone];

    [obj setWeight:_weight];

    return obj;

}


-(id)mutableCopyWithZone:(NSZone *)zone{

    id obj = [supercopyWithZone:zone];

    [obj setWeight:_weight];

    return obj;

}


- (NSString *)description

{

    return [NSStringstringWithFormat:@"name = %@age = %iweight = %lf",[selfname],[selfage],_weight];

}


@end


int main(int argc,const char * argv[]) {

    /*1Copy:需要遵守NSCopy协议,实现copyWithZone方法

        mutableCopy:需要遵守NSMutableCopy协议,实现mutableCopyWithZone方法,mutableCopyWithZone方法

     */

    Person *person1 = [Personnew];

    person1.name = @"ljs1";

    person1.age = 10;

    Person *newPerson1 = [person1 copy];

    newPerson1.age = 19;

    NSLog(@"%@",[person1description]);

    NSLog(@"%@",[newPerson1description]);

    

    Person *person2 = [Personnew];

    person2.name = @"ljs2";

    person2.age = 10;

    Person *newPerson2 = [person2 mutableCopy];

    newPerson2.age = 19;

    NSLog(@"%@",[person2description]);

    NSLog(@"%@",[newPerson2description]);

    

    //Copy的时候,得到子类的属性的话,需要重写copyWithZone

    Student *student1 = [Studentnew];

    student1.name = @"abc";

    student1.age = 123;

    student1.weight = 1.64;

    Student *student2 = [student1 copy];

    NSLog(@"%@",[student1description]);

    NSLog(@"%@",[student2description]);

    

    return 0;

}

//2015-12-24 09:09:19.777 18,自定义Copy[1260:46241] name = ljs1,age = 10

//2015-12-24 09:09:19.778 18,自定义Copy[1260:46241] name = ljs1,age = 19

//2015-12-24 09:09:19.778 18,自定义Copy[1260:46241] name = ljs2,age = 10

//2015-12-24 09:09:19.778 18,自定义Copy[1260:46241] name = ljs2,age = 19

//2015-12-24 09:09:19.779 18,自定义Copy[1260:46241] name = abcage = 123weight = 1.640000

//2015-12-24 09:09:19.779 18,自定义Copy[1260:46241] name = abcage = 123weight = 1.640000

//Program ended with exit code: 0

0 0
原创粉丝点击