美文网首页
(二十一)[OC高效系列]理解NSCopying协议

(二十一)[OC高效系列]理解NSCopying协议

作者: 修行猿 | 来源:发表于2016-08-18 23:10 被阅读79次

    1.NSCopying协议

    若想令自己所写的对象具有拷贝功能,则需要实现NSCopying协议

    • 实现copyWithZone方法
      • 方法中应该用全能初始化方法,来初始化待拷贝的对象
    //.h
          @interface Person : NSObject <NSCopying>
              @property (nonatomic,copy) NSString *name;
              @property (nonatomic,readonly) NSArray *friends;
              @property (nonatomic,assign) int age;
              - (instancetype)initWithName:(NSString *)name age:(int)age;
          @end
        //.m
          @interface Person ()
            @property (nonatomic,readwrite,strong) NSMutableArray *friends;
          @end
          @implementation Person
            - (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
    
    • 如果全能初始化不能满足要求,还应该手动的加上一些操作
            //.h
            @interface Person : NSObject <NSCopying>
                @property (nonatomic,copy) NSString *name;
                @property (nonatomic,readonly) NSArray *friends;
                @property (nonatomic,assign) int age;
                - (instancetype)initWithName:(NSString *)name age:(int)age;
            @end
            //.m
            @interface Person ()
              @property (nonatomic,readwrite,strong) NSMutableArray *friends;
            @end
            @implementation Person
            - (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];
                p->_friends = [_friends mutableCopy]; //额外的代码
        
                return p;
            }
        @end
    
    • 如果自定义对象分为可变版本和不可变版本,那么就要同时实现NSCopying与NSMutableCopying协议

    2.深拷贝与浅拷贝

    • 深拷贝浅拷贝的对比图


      深拷贝与浅拷贝
    • 复制对象时应该决定是深拷贝还是浅拷贝,一般情况下是浅拷贝,如果你所写的对象需要深拷贝,那么需要新增一个专门执行深拷贝的方法

    相关文章

      网友评论

          本文标题:(二十一)[OC高效系列]理解NSCopying协议

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