KDeogharkar
KDeogharkar

Reputation: 10959

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...]'

Upvotes: 0

Views: 1087

Answers (3)

user4757817
user4757817

Reputation:

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.

Upvotes: 0

WolfLink
WolfLink

Reputation: 3317

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

Upvotes: -1

MANIAK_dobrii
MANIAK_dobrii

Reputation: 6032

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.

Upvotes: 2

Related Questions