簡體   English   中英

在我的自定義alloc方法中未將其設置為'[((super或self)init…])的結果時返回'self'

[英]Returning 'self' while it is not set to the result of '[(super or self) init…]' in my custom alloc method

我使用自定義方法初始化自定義視圖:

1)在我的視圖控制器中,我正在調用自定義視圖,並將此數組傳遞給我的UIView類型的自定義類

NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"CustomViewiPhoneLayout" owner:self options:nil];

customViewObject = [[CustomView alloc] initWithArray:array];

[ParentLayout addSubview:customViewObject];

2)自定義視圖。

 -(id)initWithArray:(NSArray*)array {
      self = [array objectAtIndex:0]; // passing view as self; here it shows leak.
      if(self) {}
      return self;
  }

它給了我一個可能的泄漏,名為“ Returning 'self' while it is not set to the result of '[(super or self) init...]'

可以肯定的是,您不需要:

NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"CustomViewiPhoneLayout" owner:self options:nil];

customViewObject = [array objectAtIndex:0];

在您的代碼中,您分配一個視圖並松散分配自我。

我有同樣的問題,我通過刪除這些代碼來解決

NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"CustomViewiPhoneLayout" owner:self options:nil];
customViewObject = [array objectAtIndex:0];

從定義init方法開始。

在創建自定義視圖的地方而不是在自定義的定義主體中使用上述代碼。

編譯器抱怨是因為您使用的是init函數,而沒有使用其中一個超級函數。 盡管從邏輯上講可能是合理的,但從技術上講,它是對init函數的濫用,這就是編譯器抱怨的原因。 這並不總是一個問題(我有一些代碼在修復它之前僅向我發出警告),但是這是一個很好的習慣,不要那樣做。 在這種情況下,不能正確使用init函數。 我會寫這樣的另一個函數:

+(customViewObject *)createWithArray:(NSArray *)array{
     customViewObject *returnObject = [array objectAtIndex:0];
     return returnObject;
}

但是,查看代碼的第一部分,我發現不需要在customViewObject類中具有此類功能。 我建議簡單地這樣做:

NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"CustomViewiPhoneLayout" owner:self options:nil];

customViewObject = [array objectAtIndex:0];

[ParentLayout addSubview:customViewObject];

暫無
暫無

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

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