CopyWithZone returns a superclass object

I have a class hierarchy:

  • ClassA inherits from NSObject
  • ClassB inherits from ClassA
  • ClassA implements copyWithZone: as follows:

implementation:

 -(id)copyWithZone:(NSZone *)zone { ClassA *clone = [[ClassA allocWithZone:zone] init]; // other statements return clone; } 

ClassB implements the same method as this

 -(id)copyWithZone:(NSZone *)zone { ClassB *clone = [super copyWithZone:zone]; // other statements return clone; } 

ClassC has the following property:

 @property(nonatomic, copy) ClassA *classA; 

so when i do something like this:

  ClassB *classBPtr = [[ClassB alloc] init]; ClassC *classCPtr = [[ClassC alloc] init]; [classCPtr setClassA:classBPtr]; // other code 

somehow, the ClassA property ClassA never understands that the ClassA pointer actually points to an instance of ClassB . so if I call a method on ClassA , it will only call the base class implementation (one in ClassA ) instead of the derived class implementation in ClassB

any ideas i could have messed up with this?

+8
objective-c iphone
source share
2 answers

Try to change

 ClassA *clone = [[ClassA allocWithZone:zone] init]; 

to

 ClassA *clone = [[[self class] allocWithZone:zone] init]; 
+22
source share
 ClassA -(id)copyWithZone:(NSZone *)zone { ClassA *copyObject = NSCopyObject(self, 0, zone); //copy ClassA members here return copyObject; } ClassB -(id)copyWithZone:(NSZone *)zone { ClassB *copyObject = [super copyWithZone:zone]; //copy ClassB members here return copyObject; } 
+2
source share

All Articles