您的位置:首页 > 其它

View Controller 的生命周期

2014-12-08 22:24 316 查看
# View Controller 生命周期

- View Controller 拥有生命周期

即,程序运行过程中,会调用(回调)一写方法,在 apple 上也叫向对象发送消息

- 生命周期的作用

你可以重写相关的方法,去完成特定的工作

###生命周期

**开始实例化**

-

**awakeFromNib** and **outlets get set**

Anything that would go in your Controller’s init method would have to go in awakeFromNib too (because init methods are not called on objects that come out of a storyboard).

```

-(void)setup{}; //dosomethingwhichcan’twaituntilviewDidLoad

- (void)awakeFromNib { [self setup]; }

// UIViewController’s designated initializer is initWithNibName:bundle: (ugh!)

- (instancetype)initWithNibName:(NSString *)name bundle:(NSBundle *)bundle

{

self = [super initWithNibName:name bundle:bundle];

[self setup];

return self;

}

```

**viewDidLoad**

```

- (void)viewDidLoad

{

[super viewDidLoad]; // always let super have a chance in lifecycle methods

// do some setup of my MVC

}

```

view的几何属性(bounds)还没有设置

此时,你不能确定现在是在 iphone5大小的屏幕 还是 ipad or???

所以不要初始化geometry-dependent的属性

可以在此处添加各种UI子控件。

**viewWillLayoutSubviews:** and **viewDidLayoutSubviews:**

(next group can happen repeatedly as your MVC appears and disappears from the screen ...)

**viewWillAppear:**and **viewDidAppear:**

*(next group can happen repeatedly as your MVC appears and disappears from the screen ...)*

```

- (void)viewWillAppear:(BOOL)animated;

```

View 只会 "loaded" 一次,但是可能"appear" "disappear" 很多次。

不应该把放在 viewDidLoad 中的代码放到此处。

此处应该纺织一些当你的 MVC 离开屏幕时的处理

以后可以使用这个函数进行性能优化,使用这个函数(而不是 viewDidLoad)启动耗时的操作(可能在其他的线程)

view 的 geometry 在此处设置,屏幕**渲染**

**viewWillLayoutSubviews:** and **viewDidLayoutSubviews:**

(whenever geometry changes again while visible, e.g. device rotation)

**viewWillDisappear:**and **viewDidDisappear:**

(if it is autorotation, then you also get will/didRotateTo/From messages--rare to use these)

```

- (void)viewWillDisappear:(BOOL)animated

{

[super viewWillDisappear:animated]; // call super in all the viewWill/Did... methods

// let’s be nice to the user and remember the scroll position they were at ...

[self rememberScrollPosition]; // we’ll have to implement this, of course

// do some other clean up now that we’ve been removed from the screen

[self saveDataToPermanentStore]; // maybe do in did instead?

// but be careful not to do anything time-consuming here, or app will be sluggish

// maybe even kick off a thread to do what needs doing here (again, we’ll cover threads later)

}

```

**didReceiveMemoryWarning**

This rarely happens, but well-designed code with big-ticket memory uses might anticipate it. Examples: images and sounds.

Anything “big” that can be recreated should probably be released (i.e. set strong pointer to nil).

-

没有“unload”之类的,到此结束。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: