在第二次发生条件时或在超时后调用方法,以先到者为准

时间:2011-03-22 19:57:09

标签: objective-c cocoa timer notifications

在过去几天经过大量编码后,我终于(嗯)陷入困境。

我的应用程序侦听iTunes发送的外部NSNotification。每当当前播放状态改变时发送通知,在这种情况下最有趣的是当前流标题改变时。当您连接到新的广播电台时,通常会发送两个通知 - 一旦iTunes连接就会发送一个,电台名称作为标题,之后很快(大约一秒钟)发送一个艺术家和当前歌曲的标题。我只对艺术家/标题组合或第二次通知感兴趣。 ,如果在暂停两秒后仍然只发送一个通知,请使用第一个。 (由于无法预先确定是否会有一两个,因此超时是我能想到的唯一方法。)

简言之,我想仅在第二次出现条件时调用方法,或者如果只发送一个通知则在两秒超时后调用。在两秒钟过后,它应该重新设置再次完成整个交易。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

这不是太复杂。您只需要挂起第一个通知,直到计时器触发或第二个通知进入。我在代码中添加的注释应该解释该过程。

- (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
}

如果有两个类型的通知,那就更简单了。您不再需要该标志,只需注册两个回调,并且只要第二个回调,您就可以使计时器无效,发布第一个通知,并使用您刚收到的信息。

答案 1 :(得分:0)

您需要创建一个数据模型,可以存储和建模通知以及它们的顺序和时间。

首先,您需要一个数据对象来存储有关通知的每个通知和数据。   - 通知对象   - 通知到达时的时间戳   - 通知类型

然后你需要一个容器对象,它可以将数据对象保存在数组中,以及启动和捕获定时器。因此,当通知到达时,它被分类,存储在数据对象中,然后将其推送到阵列上。如果是第一种类型的通知,则容器对象启动两秒计时器。如果第二种类型的另一个通知到达,则容器对象杀死计时器但是如果计时器触发,则它返回超过两秒的最后一个第一类型通知的数据对象。

触发操作后,清空容器对象并重新开始。

相关问题