28

基本的に、ある時点でview2を呼び出すview1があります(経由presentModalViewController:animated:)。view2の特定UIButtonのものが押されると、view2 は view1 の通知メソッドを呼び出し、直後に閉じられます。通知メソッドはアラートをポップアップ表示します。

通知メソッドは正常に機能し、適切に呼び出されます。問題は、view1 が作成されるたびに (一度に 1 つの view1 だけが存在する必要があります)、おそらく別のNSNotificationビューが作成されることです。 view1 を開いた回数だけ、通知メソッドから一連の同じアラート メッセージが次々と表示されます。

これが私のコードです。私が間違っていることを教えてください:

View1.m

-(void) viewDidLoad {
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(showAlert:) 
                                                 name:@"alert" 
                                               object:nil];
}

-(void) showAlert:(NSNotification*)notification {
    // (I've also tried to swap the removeObserver method from dealloc
    // to here, but it still fails to remove the observer.)
    // < UIAlertView code to pop up a message here. >
}

-(void) dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}

View2.m

-(IBAction) buttonWasTapped {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"alert" 
                                                        object:nil];
    [self dismissModalViewControllerAnimated:YES];
}

-(void) dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}
4

3 に答える 3

61

ビュー コントローラーが閉じられた後、呼び出し-deallocが自動的に行われるわけではありません。ビュー コントローラーの有効期間にはまだ「寿命」が残っている可能性があります。その時間枠では、そのView Controllerはまだその通知を購読しています。

-viewWillDisappear:またはでオブザーバーを削除する-viewDidDisappear:と、より即時の効果が得られます。

- (void) viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                    name:@"alert" 
                                                  object:nil];
}
于 2010-07-25T06:04:54.257 に答える