Question

I heard from someone that the state of a class is not yet stable inside -(id)init, so using 'self.something' is not recommended inside init, but I have a UIView subclass that need to add some subviews to itself when the class is created, so I have to use [self addSubview: subview] in init, or I have to have another initialisation method and after I create the view using:

MyView *myView = [[MyView alloc] initWithFrame:frame];

I need to call that method. Is this correct? Does initWithFrame has the same situation with init that the class is not yet stable(as it is called after alloc)? If it is, then how should I initialise subviews?

Thanks!

Was it helpful?

Solution

There is nothing wrong with using self in init. The one point of fragility is that if you use a setter method [self setFoo:...] or self.foo = ..., then you might trigger any setter logic in the class or subclass that may not be prepared for the partially initialized state.

[self addView:someView]; is not a problem. However, you might want to consider lazy loading the views instead to offload from the instantiation. It might make it easier to refactor later.

Emphasis because if your view really does always need those other views, there is no point to trying to lazy load.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top