美文网首页
如何让自己的类具有copy修饰符,如何重写带copy关键字的se

如何让自己的类具有copy修饰符,如何重写带copy关键字的se

作者: 小程故事多又多 | 来源:发表于2019-06-23 23:09 被阅读0次

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

    具体步骤
    1 声明该类遵从NSCopying协议
    2.实现NSCopying 这个协议只有一个方法

        -(id)copyWithZone:(NSZone*)zone;
    
        - (instancetype)initWithName:(NSString *)name age:(NSUInteger)age sex:(CYLSex)sex;
    

    这么实现的

        - (id)copyWithZone:(NSZone *)zone {
        CYLUser *copy = [[[self class] allocWithZone:zone] 
                         initWithName:_name
                                      age:_age
                                      sex:_sex];
        return copy;
    }
    
         - (void)setName:(NSString *)name {
        if (_name != name) {
            //[_name release];//MRC
            _name = [name copy];
        }
    }
    

    那如何确保 name 被 copy?在初始化方法(initializer)中做:

        - (instancetype)initWithName:(NSString *)name 
                                     age:(NSUInteger)age 
                                     sex:(CYLSex)sex {
             if(self = [super init]) {
                _name = [name copy];
                _age = age;
                _sex = sex;
                _friends = [[NSMutableSet alloc] init];
             }
             return self;
        }
    

    相关文章

      网友评论

          本文标题:如何让自己的类具有copy修饰符,如何重写带copy关键字的se

          本文链接:https://www.haomeiwen.com/subject/nukgqctx.html