copyWithZone returns an object of super class
I have a class hierarchy like this:
ClassA
inherits fromNSObject
ClassB
inherits fromClassA
ClassA
implementscopyWithZone:
like this:
implementation:
-(id)copyWithZone:(NSZone *)zone
{
ClassA *clone = [[ClassA allocWithZone:zone] init];
// other statements
return clone;
}
ClassB
implementions the same method like this
-(id)copyWithZone:(NSZone *)zone
{
Clas开发者_运维百科sB *clone = [super copyWithZone:zone];
// other statements
return clone;
}
ClassC
has a property like this:
@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 the classA
property of ClassC
never realizes that classA
pointer actually points to an instance of ClassB
. hence if I call a method on classA
, it would only call the base class's implementation (the one in ClassA
) instead of the derived class implementation in ClassB
any ideas where I might have messed it up?
Try changing
ClassA *clone = [[ClassA allocWithZone:zone] init];
to
ClassA *clone = [[[self class] allocWithZone:zone] init];
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;
}
精彩评论