ObjC:在init和/或initWithFrame中使用'self' [英] ObjC: using 'self' in init and/or initWithFrame:

查看:229
本文介绍了ObjC:在init和/或initWithFrame中使用'self'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说有人说一个类的状态在 - (id)init里面还不稳定,所以在init里面不建议使用'self.something',但是我有一个UIView子类,需要添加一些子视图因此我必须在init中使用[self addSubview:subview],或者我必须有另一个初始化方法,并且在创建视图之后:

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

我需要调用该方法。它是否正确? initWithFrame与init有相同的情况,类不稳定(因为它在alloc之后调用)?如果是,那么我应该如何初始化子视图?



谢谢!

解决方案

init 中使用 self 没有错。一个脆弱点是,如果你使用一个setter方法 [self setFoo:...] self.foo = ... ,那么你可能在类或子类中触发任何可能没有为部分初始化状态准备的setter逻辑。



[self addView:someView]; 不是问题。但是,您可能会考虑延迟加载视图,而不是从实例化卸载。 因为如果你的视图确实总是需要那些其他视图,没有必要尝试延迟加载。


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!

解决方案

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.

这篇关于ObjC:在init和/或initWithFrame中使用'self'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆