OC高效率52之理解NSCopying协议

#import <Foundation/Foundation.h>

@interface EOCPerson : NSObject<NSCopying,NSMutableCopying>
@property (nonatomic, copy , readonly) NSString *firstName;
@property (nonatomic, copy , readonly) NSString *lastName;
-(id)initWithFirstName:(NSString *)firstName
           andLastName:(NSString *)lastName;
-(void)addFriend:(EOCPerson *)person;
-(void)removeFriend:(EOCPerson *)person;

@end

#import "EOCPerson.h"

@implementation EOCPerson
{
    NSMutableSet *_friend;
}

-(id)initWithFirstName:(NSString *)firstName andLastName:(NSString *)lastName{
    if (self = [super init]){
        _friend = [NSMutableSet new];
        _lastName = [lastName copy];
        _firstName = [firstName copy];
    }
    return self;
}

-(void)addFriend:(EOCPerson *)person{
    [_friend addObject:person];
}
-(void)removeFriend:(EOCPerson *)person{
    [_friend removeObject:person];
}
/**
 *  NSCopying
 *
 *  @param zone
 *
 *  @return
 */
-(id)copyWithZone:(NSZone *)zone{
    EOCPerson *person = [[[self class] allocWithZone:zone]initWithFirstName:_firstName
                                                                andLastName:_lastName];
    person->_friend = [_friend mutableCopy];
    return person;
}
/**
 *  NSMutableCopying
 */
-(id)mutableCopyWithZone:(NSZone *)zone{
    return nil;
}
/**
 *  深拷贝
 */
-(id)deepCopy{
    EOCPerson *copy = [[[self class]alloc]initWithFirstName:_firstName
                                                andLastName:_lastName];
    copy->_friend = [[NSMutableSet alloc]initWithSet:_friend copyItems:YES];
    
    return copy;
}
@end

214411_nNqG_2319073.jpg

详谈深浅拷贝:

参考文章链接:http://www.cnblogs.com/langtianya/p/3722129.html

转载于:https://my.oschina.net/u/2319073/blog/625273

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值