`
webcode
  • 浏览: 5945349 次
  • 性别: Icon_minigender_1
  • 来自: 上海
文章分类
社区版块
存档分类
最新评论

View Controller Initialization

 
阅读更多

Four places to initialize things in View Controller subclasses

你有四个机会来做初始化工作

  • - (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)bundle; (i.e. override it)
  • - (void)awakeFromNib
  • - (void)viewDidLoad
  • - (void)viewWillAppear:(BOOL)animated;

Designated Initializer

Usually only for things that have to be initialized for your view controller to even “make sense”. Often thought of as the place to initialize things having to do with your Model. Definitely not for initializing things in your View (some “UI-related” things ok like self.title).

用于初始化一些跟model有关的工作.不能用来初始化跟你的view相关的东西(比如self.title之类跟UI相关的东西)

awakeFromNib

Same purpose (generally) as your designated initializer. This is called on every object that comes out of a .xib file (instead of its designated initializer!). Sometimes UIViewControllers come out of a .xib file (e.g. MainWindow.xib), but sometimes not. Usually you want your VC to work when it is alloc/inited or if it comes from a .xib. So create a method (e.g. setup) and call it from initWithNibName:bundle: and awakeFromNib.

跟之前的用途差不多.不过每次从.xib文件中反序列化的时候都会被调用(而不是在initializer里面).有时候UIViewController也会从.xib文件中取出.

<!-- p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 9.0px SimSun} span.s1 {font: 9.0px Arial} span.s2 {font: 12.0px SimSun} -->应用程序在装载 nib 文件时,会向从档案中装载的对象发送一个 awakeFromNib 消息,但只是发送给可以响应该消息的对象,且在档案中的所有对象都装载和初 始化完成后发送。当对象接收到 awakeFromNib 消息时,Cocoa 会保证对象中所有的插座实例变 量都准备好了。典型情况下,拥有 nib 文件的对象(File’s Owner)会实现 awakeFromNib 方法, 以执行插座变量和目标-动作连接准备好之后才能执行的初始化工作。

viewDidLoad

This is the best place to put non-geometry-related initialization code which pertains to your View. You might even add some more views to your hierarchy in this method (stuff you couldn’t do in IB). Wouldn’t be out of the question to put some Model initialization code here, but theoreticallythis method could be called multiple times, so don’t re-initialize something already initialized. It’s not totally unheard of to have Views which are loaded, but then never appear on screen. So consider viewWillAppear: for some things, but maybe check to avoid multiple initialization.

这是用来初始化一些跟绘图无关代码的最佳地方.你还可以为你的图层增加更多的view(那些不能在IB里面添加的东西).毋庸置疑你也可以放一些model有关的代码,不过理论上这个方法可能会被调用多次,所以不要重复初始化.还有并不是没有这种情况出现,比如说view装载以后从来没有显示过这种情况.所以这时应该考虑viewWillAppear:

viewWillAppear:

If you have initialization that depends on your View’s bounds being set, you must do it here (and not in viewDidLoad).

如果有一些必须依赖view的bounds的代码,就放这好了

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics