I've implemented NSCopying for own class and when I use this class as a property with copy attribute I'm expecting that it should use [... copy]/[... copyWithZone:] method. But it returns a reference to the same object. But if I use copy attribute for NSString it works or when I directly call copy method. My question why copy attribute is not working for own class that supports NSCopying protocol?
@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;
}
Output:
1 0
1 1
1 0
Expected output:
1 0
1 0
1 0