如何在NSNotification中传递userInfo?

Abh*_*nav 47 iphone cocoa cocoa-touch

我试图使用NSNotification发送一些数据,但卡住了.这是我的代码:

// Posting Notification
NSDictionary *orientationData;
if(iFromInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
    orientationData = [NSDictionary dictionaryWithObject:@"Right"
                                                  forKey:@"Orientation"];
}

NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter postNotificationName:@"Abhinav"
                                  object:nil
                                userInfo:orientationData];

// Adding observer
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(orientationChanged)
                                             name:@"Abhinav"
                                           object:nil];
Run Code Online (Sandbox Code Playgroud)

现在如何在我的选择器orientationChanged中获取此userInfo字典?

Jus*_*Sid 92

您将获得传递给您的函数的NSNotification对象.这包括您提供给NSNotificationCenter的名称,对象和用户信息.

- (void)orientationChanged:(NSNotification *)notification
{
    NSDictionary *dict = [notification userInfo];
}
Run Code Online (Sandbox Code Playgroud)

  • [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:@"Abhinav" object:nil]; (4认同)

Man*_*nny 23

您的选择器必须:接受参数.
例如

@selector(orientationChanged:)
Run Code Online (Sandbox Code Playgroud)

然后在方法声明中它可以接受NSNotification参数.


小智 6

您正在发布通知.请修改通知观察器,如下所示.

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:)
 name:@"Abhinav" object:nil];

- (void)orientationChanged:(NSNotification *)notification
{
    NSDictionary *dict = [notification userInfo];
}
Run Code Online (Sandbox Code Playgroud)

我希望,这个解决方案对你有用..