copyWithZone返回超类的对象

时间:2011-03-04 12:01:27

标签: iphone objective-c

我有这样的类层次结构:

  • ClassA继承自NSObject
  • ClassB继承自ClassA
  • ClassA实现copyWithZone:,如下所示:

实现:

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

ClassB实现与此相同的方法

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

ClassC有这样的属性:

@property(nonatomic, copy) ClassA *classA;

所以,当我做这样的事情时:

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

某种程度上classA的{​​{1}}属性从未意识到ClassC指针实际指向classA的实例。因此,如果我在ClassB上调用一个方法,它只会调用基类的实现(classA中的实现)而不是ClassA中的派生类实现

我可能搞砸了什么想法?

2 个答案:

答案 0 :(得分:26)

尝试更改

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

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

答案 1 :(得分:2)

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;
}