Correctly NSCopying a "parent" property so it points to its already copied parent

170 Views Asked by At

I have a class A that contains a property of class B. Class B has a weak reference to its "parent" class A. Both classes implement NSCopying.

I don't know how exactly NSCopying should be implemented in class B. I see the two obvious choices:

  1. assign the parent property to the copied class
  2. copy the parent property and assign it to the copied class

In the first case, the parent property in B will point the original A. In the second case the parent property is an entirely new copy.

How do I copy class B correctly so that the parent property will points to the newly created copy of A during the process of NSCopying?

-(id) copyWithZone:(NSZone*)zone
{
    MyClassB* copy = [[[self class] allocWithZone:zone] init];
    copy->_parent = _parent; // <<-- should reference the new copy of A, but how?
    return copy;
}

I suppose that the easiest approach would be to update the parent property from the copyWithZone: in class A. But is there any way I can do so from within class B?

1

There are 1 best solutions below

0
CodeSmile On

I remembered that this has always been a problem when unarchiving, so the only way to fix this in my case is to swizzle the copyWithZone: method in a category for the Apple class I extended, and then after receiving the copy I go through the list of class B objects and update their parent references.