当视图首次出现时,UIViewController中的哪个方法只被调用一次?
我问的原因是我需要调用NSNotificationCenter的addObserver方法,而且我只需要做一次而且,当视图看不见时,我不需要调用removeObserver。 (实际上,当视线不可见时收到通知时,我会进行一些轻微的处理。)
最佳做法是什么?我应该用什么方法打电话? 它是viewDidLoad方法 - 任何人都可以确认,如果这种方法只被调用一次,并从未调用,随后出现的视图?
Which method(s) in UIViewController is called only once, when the view is first presented?
The reason I'm asking is I need to call the addObserver method of NSNotificationCenter, and I only need to do it once And, I don't need to call removeObserver when the view goes out of sight. (Actually, I do some light processing when a notification is received when the view is out of sight.)
What is the best practice - what method should I call? Is it viewDidLoad method - can anyone confirm if this method is called only ONCE and never called when the view appears subsequently?
最满意答案
如果视图控制器以编程方式分配其资源,请创建特定于视图控制器的自定义初始化方法。 该方法应该调用超类的init方法,然后执行任何类特定的初始化。
一般来说,不要编写复杂的初始化方法。 相反,实现一个简单的初始化方法,然后为您的视图控制器的客户端提供属性来配置其行为。
2个步骤,
视图控制器调用它的loadView方法
如果视图控制器与故事板相关联,它将从故事板加载视图。 如果视图控制器未与故事板关联,则会创建一个空的UIView对象并将其分配给视图属性。
视图控制器调用其viewDidLoad方法,该方法使您的子类可以执行任何其他加载时任务。
这张图可以给你一个更好的主意
If a view controller allocates its resources programmatically, create a custom initialization method that is specific to your view controller. This method should call the super class’s init method and then perform any class specific initialization.
In general, do not write complex initialization methods. Instead, implement a simple initialization method and then provide properties for clients of your view controller to configure its behaviors.
2 steps,
The view controller calls its loadView method
If the view controller is associated with a storyboard, it loads the views from the storyboard. If the view controller is not associated with a storyboard, an empty UIView object is created and assigned to the view property.
The view controller calls its viewDidLoad method, which enables your subclass to perform any additional load-time tasks.
this diagram can give you a better idea
更多推荐
发布评论