通知中心不会调用选择器方法帮助我

时间:2013-07-10 12:16:29

标签: ios xcode selector nsnotificationcenter

- (IBAction)playOrPauseSound:(id)sender;
{ 
    [_audioPlayer play];
    [[NSNotificationCenter defaultCenter] addObserver:_audioPlayer selector:@selector(nextsong:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}

- (IBAction)nextsong:(id)sender {
    //code 
}

1 个答案:

答案 0 :(得分:1)

您应该将notificationObserver设置为self,因为这是充当观察者的对象。您还应将notificationSender设置为_audioPlayer,因为这是发送AVPlayerItemDidPlayToEndTimeNotification通知的对象。

此外,selector方法应该有一个NSNotification实例作为唯一参数。所以我很想创建一个单独的方法来处理接收通知,然后调用下一首歌曲方法,可能是:

- (void)receivedNextSongNotification:(NSNotification *)notification 
{
    [self nextsong:nil];
}

所以完整的,像这样:

- (IBAction)playOrPauseSound:(id)sender
{ 
    [_audioPlayer play]; 
    [[NSNotificationCenter defaultCenter] addObserver: self //will look for the selector in the current class
                                             selector: @selector(playerItemDidPlayToEndTime:) 
                                                 name: AVPlayerItemDidPlayToEndTimeNotification 
                                               object: _audioPlayer]; // the object that sends the notifications
}

- (void)playerItemDidPlayToEndTime:(NSNotification *)notification 
{
    [self nextsong:nil];
}

- (IBAction)nextsong:(id)sender 
{
    //code  
}

请务必在removeObserver:name:object:self取消分配前致电_audioPlayer

希望有所帮助。