OC 自定义类实现 copy

2018-07-24  本文已影响5人  CaptainRoy

想让自定义的类具备拷贝功能,则需实现 NSCopying 协议.如果自定义的对象分为可变版本与不可变版本,那么就要同时实现 NSCopying 与 NSMutableCopying 协议

具体步骤 :
1. 需声明该类遵从 NSCopying 协议
2.实现 NSCopying 协议
-(id)copyWithZone:(NSZone *)zone
#import <Foundation/Foundation.h>

@interface Person : NSObject<NSCopying,NSMutableCopying>

@property(nonatomic,readonly,copy)NSString *name;
@property(nonatomic,readonly,assign)NSUInteger age;
@property(nonatomic,readonly,assign)Gender gender;

-(instancetype)initWithName:(NSString *)name age:(NSUInteger)age gender:(Gender)gender;

-(void)introduce;

@end
#import "Person.h"

@implementation Person

-(instancetype)initWithName:(NSString *)name age:(NSUInteger)age gender:(Gender)gender
{
    self = [super init];
    if (self) {
        _name = [name copy];
        _age = age;
        _gender = gender;
    }
    return self;
}

-(void)introduce
{
    NSLog(@"自我介绍,我的名字是 : %@,年龄 : %lu,性别 : %lu",_name,(unsigned long)_age,(unsigned long)_gender);
}

-(id)copyWithZone:(NSZone *)zone
{
    Person *copy = [[[self class] allocWithZone:zone] initWithName:_name age:_age gender:_gender];
    return copy;
}

- (id)mutableCopyWithZone:(NSZone *)zone
{
    Person *copy = [[[self class] allocWithZone:zone] initWithName:_name age:_age gender:_gender];
    return copy;
}

@end
Person *roy = [[Person alloc] initWithName:@"Roy" age:18 gender:GenderMan];
Person *personCopy = [roy copy];
Person *personMCopy = [roy mutableCopy];
        
NSLog(@" %p ",roy); // 0x100735500
NSLog(@" %p ",personCopy); // 0x100735710
NSLog(@" %p ",personMCopy); // 0x100735730
上一篇下一篇

猜你喜欢

热点阅读