16

私は通常、以下のサンプルのように NSNotification を使用します。

ビューでDidLoad:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(foo:) name:kName1 object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bar:) name:kName2 object:nil];

viewDidUnload と dealloc で:

[[NSNotificationCenter defaultCenter] removeObserver:self];

しかし、友人は[[NSNotificationCenter defaultCenter] removeObserver:self];、スーパークラスの . 彼は、次のコードを使用してオブザーバーを1つずつ削除することを提案しました。

[[NSNotificationCenter defaultCenter] removeObserver:self name:kName1 object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:kName2 object:nil];

ASIHttpRequest ライブラリのコード ( https://github.com/pokeb/asi-http-request ) を確認しました。それは私の友人の提案に従います。

私の友人が正しいかどうか知りたいですか?私の意見では、現在のインスタンスはアンロードまたは解放されるため、スーパークラスの通知も役に立たない. また、システム UIViewController サブクラスの使用通知はありますか?

4

4 に答える 4

8

使用しているすべての通知を削除したい場合は、

[[NSNotificationCenter defaultCenter] removeObserver:self];

使用している特定の通知を削除したい場合は、

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

通知が不要になった場合、最初のアプローチは簡単です。

于 2012-04-06T06:19:31.300 に答える
1

オブジェクトが消えていくので[[NSNotificationCenter defaultCenter] removeObserver:self];deallocメソッドで安全に使用できます。

メソッドではViewDidUnload、コントローラーへの参照がまだ残っているため、各オブザーバーを 1 つずつ削除することをお勧めします (対応するオブザーバーをviewDidLoadすべて再度追加する必要があります)。

于 2012-04-07T14:03:55.340 に答える
0

I use the first way, I never thought about whether it was right or not. If dealloc is being called, then the object (super as well) is going to be deallocated anyway. What you definitely DON'T want is the NSNotification being sent to a deallocated instance.

于 2012-04-06T06:20:50.897 に答える