2

ビューコントローラとWebサービス間の接続レイヤーとして機能するオブジェクトがあります。このオブジェクトはデリゲートを受け取り、サーバーからデータが返されるたびにそのデリゲートに通知します。httpリクエストの実行中にデリゲートが割り当て解除されるという問題が発生しています。リクエストが返されると、オブジェクトがデリゲートのメソッドを呼び出そうとし、アプリがクラッシュします。

これを処理するための最良の方法は何ですか。デリゲートもオブジェクトを保持していることが非常に多く、周期的な依存関係が発生するため、デリゲートを保持してはならないことをいくつかの場所で読みました。したがって、デリゲートを保持できない場合、メソッドを呼び出す前に、デリゲートが割り当て解除されているかどうかを確認するにはどうすればよいですか?

@property (nonatomic, assign) NSObject<ServerConnectionDelegate>* delegate;
4

2 に答える 2

3

Usually you should use delegate pattern if life-time of the delegate is longer than lifetime of worker object. (sorry not sure about correct term here).

You have several options how to fix that:

  • As a workaround you can set connection delegate to nil in your object's dealloc method.
  • If data is required (may be for some later usage) you can use NSNotification to inform delegate for any connection events instead of delegate pattern.
  • As Jack suggested in his comment you can make your delegate a weak property of connection - that will probably be the best solution if your project is using ARC
于 2012-10-04T18:52:25.050 に答える
0

実行中のリクエストをキャンセルし、deallocメソッドでデリゲートをnilに設定する必要があります。

- (void)dealloc
{
   [yourWebServiceRequest cancelRequestAndClearDelegate]; 
   [super dealloc];
}
于 2012-10-04T18:49:26.793 に答える