类的copy和deepcopy

- (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;

}

- (void)setName:(NSString *)name {

    _name = [name copy];

}

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

    CYLUser *copy = [[[self class] allocWithZone:zone]

                     initWithName:_name

                     age:_age

                     sex:_sex];

    copy->_friends = [_friends mutableCopy];

    return copy;

}

- (id)deepCopy {

    CYLUser *copy = [[[self class] allocWithZone:zone]

                     initWithName:_name

                     age:_age

                     sex:_sex];

    copy->_friends = [[NSMutableSet alloc] initWithSet:_friends

                                             copyItems:YES];

    return copy;

}

猜你喜欢

转载自www.cnblogs.com/diyigechengxu/p/9202499.html