我已经为自己的类实现了 NSCopying,当我将此类用作具有复制属性的属性时,我期望它应该使用[... copy] / [... copyWithZone:]方法。但它返回对同一对象的引用。但是,如果我对NSString使用copy属性,它会起作用,或者当我直接调用copy方法时。我的问题为什么copy属性不适用于支持 NSCopying 协议的自己的类?
@interface A: NSObject<NSCopying>
@property(nonatomic, strong) NSNumber *num;
@end
@implementation A
- (instancetype) init {
if(self = [super init]) {
_num = @0;
}
return self;
}
- (instancetype)copyWithZone:(NSZone *)zone {
A *newA = [A new];
newA.num = [self.num copyWithZone:zone];
return newA;
}
@end
@interface B: NSObject
@property(nonatomic, copy) NSString *str;
@property(nonatomic, copy) A *objA;
@end
@implementation B
- (instancetype) init {
if(self = [super init]) {
_objA = [A new];
_str = @"0";
}
return self;
}
@end
int main(int argc, const char * argv[]) {
B *objB = [B new];
A *newA1 = objB.objA.copy;
newA1.num = @1;
NSLog(@"%@ %@", newA1.num, objB.objA.num);
A *newA = objB.objA;
NSString *newStr = objB.str;
newA.num = @1;
newStr = @"1";
NSLog(@"%@ %@", newA.num, objB.objA.num);
NSLog(@"%@ %@", newStr, objB.str);
return 0;
}
输出:
1 0
1 1
1 0
预期输出:
1 0
1 0
1 0