iPhone开发:收到通知时为nil userInfo

时间:2010-11-07 19:28:22

标签: iphone nsnotifications

我在一个操作中发布了这样的通知:

   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”是一个包含正在下载的网址的字符串,因此我会收到有关我正在等待下载的网址的通知。

选择器的实现方式如下:

   - (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

1 个答案:

答案 0 :(得分:2)

无论如何,您似乎错误地初始化了您的userInfo对象。给定的行:

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

将创建一个自动释放的NSDictionary并将其存储到本地变量。该值不会传播到您的成员变量。

假设这是一个片段,接着是例如

self.userInfo = userInfo;

将本地分配给成员,同时保留它,然后您的代码应在此行生成异常:

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

因为它试图改变不可变对象。因此,更有可能的是,userInfo的值不会被存储,并且您在那时发送消息为零。

所以,我认为 - 假设你将userInfo声明为'retain'类型属性,你想要替换:

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

使用:

self.userInfo = [NSMutableDictionary dictionaryWithObject:targetURL 
                                                        forKey:@"state"];