這不是太複雜。您只需要堅持第一個通知,直到定時器觸發或第二個通知進入。我在代碼中的註釋應解釋過程。
- (void)awakeFromNib {
// Register for the notification you're interested in
[[NSDistributedNotificationCenter defaultCenter] addObserver:self
selector:@selector(iTunesNoteCallback:)
name:NSTheiTunesNotificationImInterestedIn
object:nil]; // @"iTunes"?
}
- (void)iTunesNoteCallback:(NSNotification *)note {
// Check whether there's been a notification already
if(!gotFirstNote){
// If so, hang on to it,
gotFirstNote = YES;
self.currNote = note; // With currNote declared as a retained property
// and start a timer.
noteTimer = [NSTimer scheduledTimerWithTimeInterval:2.0
target:self
selector:@selector(actOniTunesInfo:)
userInfo:nil repeats:NO];
}
else {
// However, if we got a notification already,
// hang on to the new one,
self.currNote = note;
// stop the timer,
[noteTimer invalidate];
// and call the same method the timer would have
[self actOniTunesInfo:nil];
}
}
- (void)actOniTunesInfo:(NSTimer *)timer {
// Reset the flag
gotFirstNote = NO;
// Use currNote; doesn't matter which one it is,
// it's the best info we've gotten
}
如果有兩個類型的通知,這是更簡單。您不再需要該標誌,只需註冊兩個回調,一旦第二個回調被調用,您就可以使計時器無效,釋放第一個通知,並使用剛剛獲得的信息。
謝謝。由於相對簡單,我非常喜歡這個解決方案。 (由於線程,定時器有點棘手。) – exscape 2011-03-23 15:27:52