您的位置:首页 > 运维架构

OC高效率52之理解NSCopying协议

2016-02-27 00:00 411 查看
#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




详谈深浅拷贝:


参考文章链接:http://www.cnblogs.com/langtianya/p/3722129.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: