簡體   English   中英

UIVIew超類對象調用子類方法,而不是其自己范圍內的方法

[英]UIVIew superclass object calling subclass method instead of method in its own scope

我的超類定義了一個稱為“ commonInit”的私有方法,該方法僅在構造時調用。

超級類由2個附加類派生,每個附加類還實現一種稱為“ commonInit”的方法

在構造派生類的對象時,我在調試器中看到從超類的范圍調用子類方法。

這似乎是非常危險的行為-即使在平凡的情況下,由於巧合,您“覆蓋”了超類私有方法

如何在不重命名超類中的方法的情況下克服此行為?

例:

@interface ASuperView : UIView
@end

@implementation ASuperView
-(id)init
{
  self = [super init];
  if(self)
  {
    [self commonInit]; // BOOM - The derived view method is called in this scope
  }
  return self;
}

-(id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
  if(self)
  {
    [self commonInit];
  }
  return self;
}

-(void)commonInit
{
  //setup the view
}

@end

@interface ADerivedView : ASuperView

@end

@implementation ADerivedView
-(id)init
{
  self = [super init];
  if(self)
  {
    [self commonInit];
  }
  return self;
}

-(id)initWithFrame:(CGRect)frame
{
  self = [super initWithFrame:frame];
  if(self)
  {
    [self commonInit];
  }
  return self;
}

-(void)commonInit
{
  //setup the view for the derived view
}
@end

在此圖像中,派生自PXTextBox的PXTextMessageBox

兩者都私下聲明方法common init

在此處輸入圖片說明

obj-c中沒有“私有”方法。 充其量您可以向標頭的使用者隱藏方法的存在,但是通過設計,凡是引用了您的對象的人都可以調用它實現的任何方法,即使他們沒有在標頭中定義該方法。 最好的選擇是定義一個新方法,例如_private_commonInit,而不是在您的類標題中共享它。

我相信這實際上是設計使然。 多態甚至是最好的! .. self實際上是指最初發送消息的對象(並不總是出現self的類實例)。解決此問題的一種方法是使用與鏈接Init相同的方式鏈接commonInit。調用[super commonInit]將從子類中調用正確的方法...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM