编写高质量代码的52个有效方法

52个有效方法(22) - 理解NSCopying协议

2018-09-05  本文已影响20人  SkyMing一C
NSCopying协议
- (id)copyWithZone:(NSZone *)zone;
//.h
#import <Foundation/Foundation.h>

@interface EOCPerson : NSObject <NSCopying>

@property (nonatomic, copy, readonly) NSString *firstName;
@property (nonatomic, copy, readonly) NSString *lastName;

- (id)initWithFirstName:(NSString*)firstName 
            andLastName:(NSString*)lastName;

@end
//.m
#import "EOCPerson.h"
@interface EOCPerson ()
@property (nonatomic,readwrite,strong) NSMutableArray *friends;
@end
@implementation EOCPerson
- (instancetype)initWithName:(NSString *)name age:(int)age
{
    self = [super init];
    if (self) {
        self.name = name;
        self.age = age;
        _friends = [NSMutableArray array];
    }
    return self;
}
- (id)copyWithZone:(NSZone *)zone{
    Person *p = [[[self class] allocWithZone:zone] initWithName:_name age:_age];
    return p;
}
@end
#import <Foundation/Foundation.h>

@interface EOCPerson : NSObject <NSCopying>

@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

//.m
@interface EOCPerson ()
@property (nonatomic,readwrite,strong) NSMutableArray *friends;
@end
@implementation EOCPerson 

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

- (void)addFriend:(EOCPerson*)person {
    [_friends addObject:person];
}

- (void)removeFriend:(EOCPerson*)person {
    [_friends removeObject:person];
}

- (id)copyWithZone:(NSZone*)zone {
    EOCPerson *copy = [[[self class] allocWithZone:zone] 
                       initWithFirstName:_firstName 
                             andLastName:_lastName];
    copy->_friends = [_friends mutableCopy];//额外的代码
    return copy;
}

@end
深拷贝与浅拷贝
浅拷贝与深拷贝
copy与mutableCopy

不可变类型 变量名 = [不可变类型 copy];

不可变类型 变量名 = [可变类型 copy];

可变类型 变量名 = [不可变类型 mutableCopy];

可变类型 变量名 = [可变类型 mutableCopy];

系统非容器类对象的 copy 操作
系统容器类对象的 copy 操作
自定义对象的 copy 操作
要点
  1. 若想令自己所写的对象具有拷贝功能,则需要实现NSCopying协议。

  2. 如果自定义的对象分为可变版本与不可变版本,那么就要同时实现NSCopying与NSMutableCopying协议。

  3. 复制对象时需决定采用浅拷贝还是深拷贝,一般情况下应该尽量执行浅拷贝。

  4. 如果你所写的对象需要深拷贝,那么可考虑新增一个专门执行深拷贝的方法。

iOS - copy与mutableCopy

上一篇 下一篇

猜你喜欢

热点阅读