简体   繁体   中英

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

I init my custom view with my custom method :

1) In My View Controller I am calling custom view and pass this array to my custom class that is of type UIView

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

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

[ParentLayout addSubview:customViewObject];

2) Custom View.

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

It giving me possible leak named Returning 'self' while it is not set to the result of '[(super or self) init...]'

For sure you don't need this, as far as:

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

customViewObject = [array objectAtIndex:0];

In your code you alloc a view and loose it assigning self.

I have the same problem, i fix it by remove these code

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

from the definition init method.

use above code at the place where you create the custom view rather than in custom's definition body.

The compiler is complaining because you are using an init function without using one of the super functions. Although it may make logical sense, it is technically misuse of the init function, and this is why the compiler is complaining. This will not always be a problem (I had some code that only gave me a warning on it before I fixed it), but it is a good practice not to work that way. In this case, this is not proper use of the init function. I would write another function like this:

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

However, looking at the first bit of code, I see no need to have a function of this sort in the customViewObject class. I would recommend simply doing this:

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

customViewObject = [array objectAtIndex:0];

[ParentLayout addSubview:customViewObject];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM