gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 16:45:43 26 4
gpt4 key购买 nike

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

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

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

我添加以下方法:

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

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

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

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

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

最佳答案

您需要使用 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"];
}

关于ios - 如何访问iOS通知中传递的数据(简单)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32397669/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com