2011-01-12 9 views
1

NSNotificationQueueを使用してコアレーションを実行する次のコードを書きました。イベントが複数回発生した場合でも1つの通知のみを送信します。NSNotificationQueueを使用して結合する

- (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" 対象:自己] postingStyle:NSPostWhenIdle coalesceMask:NSNotificationCoalescingOnName forModes:nil];

ケース2: [NSNotificationQueue defaultQueue] enqueueNotification: [NSNotification notificationWithName:@ "async000" オブジェクト:自己] postingStyle:NSPostWhenIdle]。

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

答えて

6

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

はこのように2つの通知をエンキューするtest000AsyncTestingを変更、これを確認するには、次のときにポーリング
[[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回呼び出されます。

0

通知の「登録を解除する」必要があります。

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

    [super dealloc]; 
} 
+0

ここで、 ' - (void)dealloc;'の中で 'super'に' dealloc'を呼び出さなければなりません。 – Daniel

関連する問題