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

2016-08-18  本文已影响79人  修行猿

1.NSCopying协议

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

//.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

2.深拷贝与浅拷贝

上一篇 下一篇

猜你喜欢

热点阅读