viewDidLoad、viewDidUnload、viewWillAppear、viewDidAppear、viewWillDisappear 和 -viewDidDisappear的区别和使用

本文深入探讨了iOS ViewController中的关键生命周期方法,包括 viewDidLoad、viewWillAppear、viewDidAppear、viewWillDisappear 和 viewDidDisappear,以及它们在应用界面管理中的作用。通过详细解释每个方法的执行时机和用途,帮助开发者更有效地组织和执行代码逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先看一下官方解释:

- (void)loadView;// This is where subclasses should create their custom view hierarchy if they aren't using a nib. Should never be called directly.

- (void)viewDidUnloadNS_DEPRECATED_IOS(3_0,6_0);// Called after the view controller's view is released and set to nil. For example, a memory warning which causes the view to be purged. Not invoked as a result of -dealloc.

- (void)viewDidLoad;// Called after the view has been loaded. For view controllers created in code, this is after -loadView. For view controllers unarchived from a nib, this is after the view is set.

- (void)viewWillAppear:(BOOL)animated;   // Called when the view is about to made visible. Default does nothing

- (void)viewDidAppear:(BOOL)animated;    // Called when the view has been fully transitioned onto the screen. Default does nothing

- (void)viewWillDisappear:(BOOL)animated;// Called when the view is dismissed, covered or otherwise hidden. Default does nothing

- (void)viewDidDisappear:(BOOL)animated; // Called after the view was dismissed, covered or otherwise hidden. Default does nothing

-viewDidLoad,这个方法在view被加载之后调用,如果没有nib文件,这个方法是在loadView方法被调用之后调用,如果有nib文件,这个方法是在view从nib中加载后调用,总之当一个viewController被初始化后,-viewDidLoad方法仅被调用一次。

-viewWillAppear,在加载了view之后,在view出现在屏幕之前调用viewWillAppear

--viewDidAppear,view出现在屏幕之后开始调用

-viewWillDisappear,是指view将要消失的时候开始调用

-viewDidDisappear,是指view已经消失后开始调用

-viewDidUnload,是指一个view被release或被内存警告清除时调用,在dealloc后不会调用

我们会把一次执行的代码放在viewDidLoad里面,把要多次执行的代码放在viewWillAppear里面


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值