ObjC: using 'self' in init and/or initWith

2019-08-02 15:16发布

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!

1条回答
冷血范
2楼-- · 2019-08-02 16:05

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.

查看更多
登录 后发表回答