当视图首次出现时,UIViewController中的哪个方法只被调用一次?(Which method(s) in UIViewController is called only once, when

编程入门 行业动态 更新时间:2024-10-25 06:21:11
当视图首次出现时,UIViewController中的哪个方法只被调用一次?(Which method(s) in UIViewController is called only once, when the view is first presented? viewDidLoad?)

当视图首次出现时,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

enter image description here

更多推荐

本文发布于:2023-04-29 06:10:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1335250.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:首次   现时   视图   方法   view

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!