OC开发_Storyboard——视图控制生命周期以及NSNotifications

一、生命周期

1、ViewDidLoad: 一般的初始化,除了几何图形的初始化(这个时候还没确定)

2、ViewWillAppear: 代表你的视图将要在屏幕上显示,可能会调用多次,对不可见时可能能改变的内容进行同步 (例如模型改变的时候调用显示改变的数据)

3、ViewWillDisappear 不在屏幕不再占用资源时,记住、恢复、停止

4、didRecevierMemoryWarning 手机运行占用很大空间,例如图像、视频:释放内存,处理内存警告(系统决定)

具体的生命周期是这样的:

(1 从storyboard中进行实例化,或者通过调用all从或者init,

(2 如果是从storyboard中出来的,就会调用awakeFromNib,不然就是调用initWithNibName bundle

(3 viewDidLoad

(4 当几何内容被确定之后,viewWillLayoutSubview和viewDidlayoutSubviews被调用

(5.1 viewWillappear和viewDidappear会被调用

(5.2 viewWillDisappear和viewDidDisappear会被调用 (如果几何内容有变化,viewWillLayoutSubview和viewDidlayoutSubviews会再次被调用)

(6 didRecevierMemoryWarning

二、NSNotifications 广播站机制(通知)

结束收听之后,要移除自己【不安全指针】,可以在dealloc移除

例子:

 1 //
 2 //  ViewController.m
 3 //  testForNotification
 4 //
 5 //  Created by bos on 15-4-14.
 6 //  Copyright (c) 2015年 axiba. All rights reserved.
 7 //
 8 
 9 #import "ViewController.h"
10 
11 @interface ViewController ()
12 @property (weak, nonatomic) IBOutlet UITextView *content;
13 @property (weak, nonatomic) IBOutlet UILabel *headLine;
14 
15 @end
16 
17 @implementation ViewController
18 
19 - (IBAction)changeTextColorByClickButton:(UIButton*)sender {
20     
21     //control the range of our select
22     [self.content.textStorage addAttribute:NSForegroundColorAttributeName
23                                      value:sender.backgroundColor
24                                      range:self.content.selectedRange];
25     
26 }
27 
28 - (void)viewDidLoad {
29     [super viewDidLoad];
30     // Do any additional setup after loading the view, typically from a nib.
31     
32 }
33 
34 
35 #pragma the view appear
36 -(void)viewWillAppear:(BOOL)animated
37 {
38     [super viewWillAppear:animated];
39     [[NSNotificationCenter defaultCenter] addObserver:self
40                                              selector:@selector(setUserPreferFont)
41                                                  name:UIContentSizeCategoryDidChangeNotification
42                                                object:nil];
43     
44 }
45 
46 #pragma  the view disappear then remove it 
47 -(void)viewWillDisappear:(BOOL)animated
48 {
49     [super viewWillDisappear:animated];
50     [[NSNotificationCenter defaultCenter] addObserver:self
51                                              selector:@selector(setUserPreferFont)
52                                                  name:UIContentSizeCategoryDidChangeNotification
53                                                object:nil];
54 }
55 -(void)setUserPreferFont
56 {
57     self.headLine.font = [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline];
58     self.content.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
59 }
60 
61 - (void)didReceiveMemoryWarning {
62     [super didReceiveMemoryWarning];
63     // Dispose of any resources that can be recreated.
64 }
65 
66 @end
原文地址:https://www.cnblogs.com/daomul/p/4426063.html