NSNotificationCenter删除了错误的观察者?

时间:2012-10-10 01:52:30

标签: ios nsnotificationcenter nsnotifications

removeObserver是否有任何角落案例行为:name:object:?在下面的代码块中,我的观察者没有正确注册:

- (void)setPlayerItem:(AVPlayerItem *)playerItem {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(playerItemDidReachEnd:)
                                                 name:nil
                                               object:playerItem];

    [playerItem addObserver:self
                 forKeyPath:kStatus
                    options:0
                    context:(__bridge void*)self];

    [playerItem addObserver:self
                 forKeyPath:kPlaybackBufferEmpty
                    options:0
                    context:(__bridge void*)self]; // For adding a buffering activity indicator

    id temp = playerItem_;
    playerItem_ = [playerItem retain];

    [[NSNotificationCenter defaultCenter] removeObserver:self name:nil object:temp];
    [temp removeObserver:self forKeyPath:kPlaybackBufferEmpty];
    [temp removeObserver:self forKeyPath:kStatus];
    [temp release];
}

但是,如果我将订单更改为:

- (void)setPlayerItem:(AVPlayerItem *)playerItem {    
    [playerItem addObserver:self
                 forKeyPath:kStatus
                    options:0
                    context:(__bridge void*)self];

    [playerItem addObserver:self
                 forKeyPath:kPlaybackBufferEmpty
                    options:0
                    context:(__bridge void*)self]; // For adding a buffering activity indicator

    id temp = playerItem_;
    playerItem_ = [playerItem retain];

    [[NSNotificationCenter defaultCenter] removeObserver:self name:nil object:temp];
    [temp removeObserver:self forKeyPath:kPlaybackBufferEmpty];
    [temp removeObserver:self forKeyPath:kStatus];
    [temp release];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(playerItemDidReachEnd:)
                                                 name:nil
                                               object:playerItem];
}

所有通知都很好。这让我相信当我打电话时会发生一些奇怪的事情:

    [[NSNotificationCenter defaultCenter] removeObserver:self name:nil object:temp];

我错过了一些非常明显的东西吗?我在iOS 6上没有ARC。

3 个答案:

答案 0 :(得分:1)

找到答案。事实证明,它与传递nil观察者名称有关。 致电[[NSNotificationCenter defaultCenter] removeObserver:self name:nil object:temp]; 将删除self以免观察temp发布的任何通知。 但是,在临界值为nil的情况下,这行代码将同时删除self作为观察者。

答案 1 :(得分:0)

名称不应为零。你试过给观察者一个名字吗?

答案 2 :(得分:0)

@Lee是正确的,名称不应该是nil,但它也不应该是观察者的名字。相反,它应该是您要注册观察的通知的名称。例如,UIDeviceOrientationDidChangeNotification。 添加要在该参数中观察的通知的名称,并在删除观察者时将其作为名称参数传递