playerken

博客园 首页 新随笔 联系 订阅 管理

When an iOS application is launched, it starts a run loop. The run loop’s job is to listen for events,
such as a touch. When an event occurs, the run loop then finds the appropriate handler methods for the
event. Those handler methods call other methods, which call more methods, and so on. Once all of the
methods have completed, control returns to the run loop.
When the run loop regains control, it checks a list of “dirty views” – views that need to be rerendered
based on what happened in the most recent round of event handling. The run loop then sends
the drawRect: message to the views in this list before all of the views in the hierarchy are composited
together again.

 

These two optimizations – only re-rendering views that need it and only sending drawRect: once per
event – keep iOS interfaces responsive.

 

To get a view on the list of dirty views, you must send it the message setNeedsDisplay. The
subclasses of UIView that are part of the iOS SDK send themselves setNeedsDisplay whenever their
content changes.

 

For example, an instance of UILabel will send itself setNeedsDisplay when it is sent
setText:, since changing the text of a label requires the label to re-render its layer. In custom UIView
subclasses, you must send this message yourself.

There is another possible optimization when redrawing: you can mark only a portion of a view as
needing to be redrawn. This is done by sending setNeedsDisplayInRect: to a view.

 

Often, you will want to do some extra initialization of the subviews that are defined in the XIB file
before they appear to the user. However, you cannot do this in the view controller’s initializer
because the NIB file has not yet been loaded. If you try, any pointers that the view controller declares
that will eventually point to subviews will be pointing to nil. The compiler will not complain if you
send a message to one of these pointers, but whatever you intended to happen to that view object will
not happen.
So where can you access a subview? There are two main options, depending on what you need to do.
The first option is the viewDidLoad method that you overrode to spot lazy loading. The view
controller receives this message after the view controller’s NIB file is loaded, at which point all of
the view controller’s pointers will be pointing to the appropriate objects. The second option is
another UIViewController method viewWillAppear:. The view controller receives this message just
before its view is added to the window.
What is the difference? You override viewDidLoad if the configuration only needs to be done once
during the run of the app. You override viewWillAppear:

if you need the configuration to be done and
redone every time the view controller appears on screen.

posted on 2014-12-08 14:23  playerken  阅读(117)  评论(0编辑  收藏  举报