1

私はこのような通知を操作で投稿します:

   DownloadStatus * status = [[DownloadStatus alloc] init];
   [status setMessage: @"Download started"];
   [status setStarted];
   [status setCompleteSize: [filesize intValue]];
   [userInfo setValue:status forKey:@"state"];
   [[NSNotificationCenter defaultCenter]
       postNotificationName:[targetURL absoluteString]
       object:nil userInfo:userInfo];
   [status release];

DownloadStatusは、現在ダウンロードされているダウンロードに関する情報を含むオブジェクトです。userInfoは、init部分で初期化され、操作の全期間にわたって保持されるオブジェクトのプロパティです。それは次のように作成されます:

 NSDictionary * userInfo = [NSDictionary dictionaryWithObject:targetURL 
                                                             forKey:@"state"];

「targetURL」はNSStringです。これは、すべてが正常に機能していることを確認するためだけに使用します。イベントを受け取ったとき-私は次のように登録しました:

   [[NSNotificationCenter defaultCenter] 
       addObserver:self selector:@selector(downloadStatusUpdate:) 
       name:videoUrl 
       object:nil];

ここで、「videoUrl」はダウンロード中のURLを含む文字列であるため、ダウンロードされるのを待っているURLに関する通知を受け取ります。

セレクターは次のように実装されます。

   - (void) downloadStatusUpdate:(NSNotification*) note   {

     NSDictionary * ui = note.userInfo; // Tried also [note userInfo]

     if ( ui == nil ) {
         DLog(@"Received an update message without userInfo!");
         return;
     }
     DownloadStatus * state = [[ui allValues] objectAtIndex:0];
     if ( state == nil ) {
         DLog(@"Received notification without state!");
         return;
     }
     DLog(@"Status message: %@", state.message);
     [state release], state = nil;
     [ui release], ui = nil;   }

ただし、このセレクターは常にnullのuserInfoを受け取ります。私は何が間違っているのですか?

MrWHO

4

1 に答える 1

2

どういうわけか、userInfoオブジェクトを誤って初期化しているようです。与えられた行:

NSDictionary * userInfo = [NSDictionary dictionaryWithObject:targetURL 
                                                        forKey:@"state"];

自動リリースされたNSDictionaryを作成し、ローカル変数に保存します。値はメンバー変数まで伝播されません。

それがスニペットであり、その後に例が続くと仮定します

self.userInfo = userInfo;

ローカルをメンバーに割り当て、同時にそれを保持するには、コードは次の行で例外を生成する必要があります。

[userInfo setValue:status forKey:@"state"];

不変オブジェクトを変更しようとするためです。したがって、userInfoの値が保存されておらず、その時点でメッセージがnilである可能性がはるかに高くなります。

したがって、userInfoが「retain」タイプのプロパティとして宣言されていると仮定すると、次のように置き換えたいと思います。

NSDictionary * userInfo = [NSDictionary dictionaryWithObject:targetURL 
                                                        forKey:@"state"];

と:

self.userInfo = [NSMutableDictionary dictionaryWithObject:targetURL 
                                                        forKey:@"state"];
于 2010-11-07T19:41:59.903 に答える