0

パーサークラスといくつかのビューコントローラークラスがあります。パーサークラスでは、要求を送信し、非同期応答を受信して​​います。ビューコントローラごとに1つずつ、複数のダウンロードが必要です。だから私はこれらのクラスのそれぞれにオブザーバーを登録します:

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dataDownloadComplete:) name:OP_DataComplete object:nil];

次に、次の場所に通知を投稿します。

-(void)connectionDidFinishLoading:(NSURLConnection *)connection method of the parser class.
[[NSNotificationCenter defaultCenter] postNotificationName:OP_DataComplete object:nil];

しかし、コードを実行すると、最初のビューコントローラーは正常に機能しますが、ダウンロードとパーサークラスの投稿通知の後、2番目以降は、セレクターで毎回異なるメソッド名を指定していますが、コードは最初のクラスのdataDownloadComplete:メソッドに入ります。エラーが何であるかわかりません。助けてください。前もって感謝します。

4

2 に答える 2

1

両方のView Controllerが通知をリッスンしているため、両方のメソッドを次々に呼び出す必要があります。

これを解決するにはいくつかの方法があります。最も簡単な方法は、View Controller がそれを無視する必要があるかどうかを確認できる何らかの識別子を通知に含めることです。NSNotifications には、このための userInfo プロパティがあります。

NSDictionary *info = [NSDictionary dictionaryWithObjectsAndKeys:@"viewController1", @"id", nil];
[[NSNotificationCenter defaultCenter] postNotificationName:OP_DataComplete object:self userInfo:info];

通知を受け取ったら、それが誰のためのものかを確認してください。

- (void)dataDownloadComplete:(NSNotification *)notification {
    NSString *id = [[notification userInfo] objectForKey:@"id"];
    if (NO == [id isEqualToString:@"viewController1"]) return;

    // Deal with the notification here
    ...
}

object:selfそれに対処する方法は他にもいくつかありobject:nilますが、コードについて詳しく知らないと、うまく説明できません.あなたのアーキテクチャはそれを許しません。

于 2011-04-08T08:56:11.313 に答える
0

プロトコルを作成することをお勧めします。

@protocol MONStuffParserRecipientProtocol
@required
- (void)parsedStuffIsReady:(NSDictionary *)parsedStuff;
@end

ビューコントローラーを宣言するには:

@class MONStuffDownloadAndParserOperation;

@interface MONViewController : UIViewController < MONStuffParserRecipientProtocol >
{
  MONStuffDownloadAndParserOperation * operation; // add property
}
...
- (void)parsedStuffIsReady:(NSDictionary *)parsedStuff; // implement protocol

@end

いくつかのバックエンドを追加します:View Controllerに

- (void)displayDataAtURL:(NSURL *)url
{
    MONStuffDownloadAndParserOperation * op = self.operation;
    if (op) {
        [op cancel];
    }

    [self putUpLoadingIndicator];

    MONStuffDownloadAndParserOperation * next = [[MONStuffDownloadAndParserOperation alloc] initWithURL:url recipient:viewController];
    self.operation = next;
    [next release], next = 0;
}

操作をView Controllerに保持させます:

@interface MONStuffDownloadAndParserOperation : NSOperation
{
  NSObject<MONStuffParserRecipientProtocol>* recipient; // << retained
}

- (id)initWithURL:(NSURL *)url Recipient:(NSObject<MONStuffParserRecipientProtocol>*)recipient;

@end

データがダウンロードされて解析されると、操作メッセージが受信者に送信されます。

// you may want to message from the main thread, if there are ui updates
[recipient parsedStuffIsReady:parsedStuff];

実装するものは他にもいくつかあります。これは単なるフォームです。より安全で、ダイレクト メッセージ、参照カウント、キャンセルなどが含まれます。

于 2011-04-08T09:10:56.990 に答える