【问题标题】:How to access data passed in iOS notification (simple)?如何访问iOS通知中传递的数据(简单)?
【发布时间】:2015-11-30 14:08:40
【问题描述】:

试图让一个 ViewController 通过标准的 Cocoa Notifications 与另一个 ViewController 通信。

写了一个简单的测试用例。在我最初的 VC 中,我将以下内容添加到 viewDidLoad:

[[NSNotificationCenter defaultCenter] addObserver:self 
 selector: @selector(mesageReceived:)
 name:@"test.channel.pw" object:nil];

我添加以下方法:

- (void)mesageReceived:(NSNotification *)notif
{
    NSString *text = (NSString *)notif;    
}

然后我转到一个在其 viewDidLoad 中添加了以下内容的 VC:

  NSString *test = @"someText";
 [[NSNotificationCenter defaultCenter]
     postNotificationName:@"test.channel.pw" object:test];

当我运行它时,通知起作用了——messageReceived 方法被调用——但是文本的值是“test.channel.pw”,而不是我预期的“someText”。

这里发生了什么,使用通知传递对类实例的引用的正确语法是什么?

【问题讨论】:

标签: ios cocoa nsnotificationcenter nsnotification


【解决方案1】:

您需要使用userInfo 字典传递您的数据。

更改通知传递代码,如:

[[NSNotificationCenter defaultCenter] postNotificationName:@"test.channel.pw" object:nil userInfo:[NSDictionary dictionaryWithObject:@"someText" forKey:@"dataKey"]];

并更改接收器方法,如:

- (void)mesageReceived:(NSNotification *)notif
{
    NSString *text = [[notif userInfo] objectForKey:@"dataKey"];    
}

【讨论】:

    【解决方案2】:

    试试NSString *text = (NSString *)[notif object];

    【讨论】:

      【解决方案3】:

      由此

      -(void)someMethod{
        NSDictionary *postDict = @{@"Key":[NSNumber numberWithFloat:17.0]};
      [[NSNotificationCenter defaultCenter]postNotificationName:@"myNotification" object:postDict];
      }
      

      其他类

      -(void)viewDidLoad{
      [[NSNotificationCenter defaultCenter]postNotificationName:@"myNotification" object:nil userInfo:postDict];
      }
      -(void)valueForNotification:(NSNotification *)notification{
      NSDictionary *dict = [notification userInfo];
      NSLog(@"%@",[dict objectForKey:@"Key"]); //prints out 17.0
      }
      

      【讨论】:

        【解决方案4】:

        您只需要在 NSnotificationCenter 中传递 NSDictionary 对象。通过 NSDictionary 你可以传递任何数据,然后你需要在收到后解析。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-03-04
          • 2023-01-30
          • 1970-01-01
          相关资源
          最近更新 更多