Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何访问iOS通知中传递的数据(简单)?_Ios_Cocoa_Nsnotificationcenter_Nsnotification - Fatal编程技术网

如何访问iOS通知中传递的数据(简单)?

如何访问iOS通知中传递的数据(简单)?,ios,cocoa,nsnotificationcenter,nsnotification,Ios,Cocoa,Nsnotificationcenter,Nsnotification,试图让一个ViewController通过标准Cocoa通知与另一个进行通信 编写了一个简单的测试用例。在我的初始VC中,我向viewDidLoad添加了以下内容: [[NSNotificationCenter defaultCenter] addObserver:self selector: @selector(mesageReceived:) name:@"test.channel.pw" object:nil]; NSString *test = @"someText"; [

试图让一个ViewController通过标准Cocoa通知与另一个进行通信

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

[[NSNotificationCenter defaultCenter] addObserver:self 
 selector: @selector(mesageReceived:)
 name:@"test.channel.pw" object:nil];
  NSString *test = @"someText";
 [[NSNotificationCenter defaultCenter]
     postNotificationName:@"test.channel.pw" object:test];
我添加以下方法:

- (void)mesageReceived:(NSNotification *)notif
{
    NSString *text = (NSString *)notif;    
}
然后我转到一个VC,它的viewDidLoad中添加了以下内容:

[[NSNotificationCenter defaultCenter] addObserver:self 
 selector: @selector(mesageReceived:)
 name:@"test.channel.pw" object:nil];
  NSString *test = @"someText";
 [[NSNotificationCenter defaultCenter]
     postNotificationName:@"test.channel.pw" object:test];
当我运行它时,通知会起作用——调用messageReceived方法——但是文本的值是“test.channel.pw”,而不是我所期望的“someText”


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

您需要使用字典传递数据

更改通知传递代码,如下所示:

[[NSNotificationCenter defaultCenter] postNotificationName:@"test.channel.pw" object:nil userInfo:[NSDictionary dictionaryWithObject:@"someText" forKey:@"dataKey"]];
并更改接收器方法,如:

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

尝试
NSString*text=(NSString*)[notif对象]

通过此

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

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

数据可能重复