【发布时间】:2015-12-02 18:19:39
【问题描述】:
我正在尝试将 NSString 从一个类传递到另一个类。假设我有 ViewController A 和 ViewController B。我想将 NSString 从 A 传递到 B。
在 ViewController A 中,我有以下代码:
[[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationMessageEvent" object:userType];
//这里的用户类型是我使用委托得到的字符串,我需要将此用户类型传递给ViewController B
在 ViewController B 中,我有以下代码: 在 viewDidLoad 中,我有以下代码:
[NSNotificationCenter defaultCenter]
addObserver:self selector:@selector(notificationAction:) name:@"NotificationMessageEvent" object:nil];
//这个NSNotificationCenter方法被调用
我已经注册了以下选择器方法。
-(void) notificationAction:(NSNotification *) notification
{
if ([notification.object isKindOfClass:[NSString class]])
{
NSString *message = [notification object];
// do stuff here with your message data
NSLog(@"%@ is message",message);
}
else
{
NSLog(@"Error, object not recognised.");
}
}
//上面的选择器方法永远不会被调用。
我已经阅读了其他类似的 stackoverflow 答案,但我无法找到任何关于此的解决方案。
【问题讨论】:
-
为了实际添加上述通知选择器,必须调用 ViewController B 的 viewDidLoad(也就是必须显示视图)
-
感谢您澄清@Hayden Holligan。我实际上是在 B 之前加载 A。
-
虽然您的代码有效,但请不要以这种方式使用通知对象。在这种情况下,对象是通知实例的发送者。使用 userInfo 在对象之间传递一些信息。
-
在我的例子中,我在本地方法中创建了一个对象,所以观察者类在通知期间从另一个类触发。你可以检查这个:stackoverflow.com/questions/67328439/…
标签: ios objective-c iphone xcode nsnotificationcenter