开发者

copyWithZone returns an object of super class

I have a class hierarchy like this:

  • ClassA inherits from NSObject
  • ClassB inherits from ClassA
  • ClassA implements copyWithZone: 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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜