读书人

IOS4 note 12 (三)

发布时间: 2012-06-27 14:20:08 作者: rapoo

IOS4 note 12 (3)

NSTimer

?

An timer (NSTimer) is not, strictly speaking, a notification; but it behaves very similarly. It is an object that gives off a signal (fires) after the lapse of a certain time interval.?The signal is a message to one of your instances. Thus you can arrange to be notified?when a certain time has elapsed. The timing is not perfectly accurate, but it’s pretty?good.

?

Timer management is not exactly tricky, but it is a little unusual. A timer that is actively?watching the clock is said to be scheduled. A timer may fire once, or it may be a repeating timer. To make a timer go out of existence, it must be invalidated. A timer that is?set to fire once is invalidated automatically after it fires; a repeating timer repeats until?you invalidate it (by sending it the invalidate message). An invalidated timer should?be regarded as off-limits: you cannot revive it or use it for anything further, and you?should probably not send any messages to it.

The straightforward way to create a timer is with the NSTimer class method scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:. ?This creates the timer?and ?schedules it, so that it begins watching the clock immediately. The target and?selector determine what message will be sent to what object when the timer fires; the?method in question should take one parameter, which will be a reference to the timer.?The userInfo is just like the userInfo of a notification. (You can see why I categorize?timers as being similar to notifications.)

?

Delegation

Delegation is an object-oriented design pattern, a relationship between two objects, in?which the first object’s behavior is customized or assisted by the second. The second?object is the first object’s delegate. No subclassing is involved, and indeed the first object?is agnostic about the second object’s class.

A built-in Cocoa class has an?instance variable, usually called delegate (it will certainly have delegate in its name).?For some instance of that Cocoa class, you set the value of this instance variable to an?instance of one of ?your ?classes. At ?certain moments ?in ?its ?activity, ?the Cocoa ?class?promises to turn to its delegate for instructions by sending it a certain message: if the?Cocoa ?instance ?finds ?that ?its delegate ?is not nil, and ?that ?its delegate ?is prepared ?to?receive ?that message, ?the Cocoa ?instance?sends the message to the delegate.

The ?UIApplication ?delegate ?methods ?are ?also ?provided ?as ?notifications. This lets an instance other than the app delegate hear conveniently?about application lifetime events, by registering for them. A few other?classes provide duplicate events similarly; for example, UITableView’s?delegate method tableView:didSelectRowAtIndexPath: is matched by a?notification UITableViewSelectionDidChangeNotification.

?

读书人网 >操作系统

热点推荐