1

NSNotificationQueueを使って合体するコードを書いてみました。イベントが複数回発生しても通知を1つだけ投稿したい。

- (void) test000AsyncTesting
{
    [NSRunLoop currentRunLoop];
    [[NSNotificationCenter defaultCenter] addObserver:self             selector:@selector(async000:) name:@"async000" object:self];
    [[NSNotificationQueue defaultQueue] enqueueNotification:[NSNotification notificationWithName:@"async000" object:self]
    postingStyle:NSPostWhenIdle coalesceMask:NSNotificationCoalescingOnName forModes:nil];

    while (i<2)
    {
        [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0]];
        NSLog(@"Polling...");
        i++;
    }
}

- (void) async000:(NSNotification*)notification;
{
    NSLog(@"NSNotificationQueue");
}

メソッド「test000AsyncTesting」を呼び出すたびに、同じ名前の通知がキューに追加されます。合体の概念に従って、キューに任意の数の通知があるが同じ名前の場合、一度だけ投稿されます。しかし、コードを実行すると、「async000:」が複数回呼び出されます。これは、NSNotificationQueue に追加された通知の数とまったく同じです。合体が機能していないと思います。
私にとって、コードの実行はこれらのケースの両方で同じままです:

ケース 1: [[NSNotificationQueue defaultQueue] enqueueNotification:[NSNotification notificationWithName:@"async000" object:self] postedStyle:NSPostWhenIdle coalesceMask:NSNotificationCoalescingOnName forModes:nil];

ケース 2: [[NSNotificationQueue defaultQueue] enqueueNotification: [NSNotification notificationWithName:@"async000" object:self] postedStyle:NSPostWhenIdle];

私のコードのエラーを教えてください。

4

2 に答える 2

7

合体は、制御フローが実行ループに戻るまで発生する通知のみを結合します。実行ループを介して後続のトリップで通知をキューに入れると、別の通知呼び出しが発生します。

これを確認するには、test000AsyncTesting を次のように 2 つの通知をキューに入れるように変更します。

[[NSNotificationQueue defaultQueue] enqueueNotification:[NSNotification notificationWithName:@"async000" object:self]
postingStyle:NSPostWhenIdle coalesceMask:NSNotificationCoalescingOnName forModes:nil];

[[NSNotificationQueue defaultQueue] enqueueNotification:[NSNotification notificationWithName:@"async000" object:self]
postingStyle:NSPostWhenIdle coalesceMask:NSNotificationCoalescingOnName forModes:nil];

その後async000、ポーリング時に一度だけ呼び出されます。

テストのために、coalesceMask を NSNotificationNoCoalescing に変更すると、ポーリング時に async000 への 2 つの呼び出しが表示されます。

于 2011-01-20T18:57:11.280 に答える
0

通知を「登録解除」する必要があります。これを試して:

-(void)dealloc
{    
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"async000" object:nil];

    [super dealloc];
}
于 2012-07-04T17:12:22.997 に答える