如何在Objective-C上发送带参数的通知?

Dmi*_*try 7 iphone notifications ios

我需要将@"willAnimateRotationToInterfaceOrientation"带有参数toInterfaceOrientationduration(问题#1)的通知发送给UIViewController应用程序上的所有人(问题#2).如何为此编写代码?

[[NSNotificationCenter defaultCenter]
  addObserver:self
     selector:@selector(willAnimateRotationToInterfaceOrientation:toInterfaceOrientation:duration)
         name:@"willAnimateRotationToInterfaceOrientation"
       object:nil];

[[NSNotificationCenter defaultCenter] 
  postNotificationName:@"willAnimateRotationToInterfaceOrientation"
                object:self];
Run Code Online (Sandbox Code Playgroud)

Gab*_*lla 19

使用postNotificationName:object:userInfo:并捆绑您希望在userInfo字典中传递的任何参数.

例:

你可以发布这样的通知

NSDictionary * userInfo = @{ @"toOrientation" : @(toOrientation) };
[[NSNotificationCenter defaultCenter] postNotificationName:@"willAnimateRotationToInterfaceOrientation" object:nil userInfo:userInfo];
Run Code Online (Sandbox Code Playgroud)

然后通过执行以下操作检索您传递的信息:

- (void)willAnimateRotationToInterfaceOrientation:(NSNotification *)n {
    UIInterfaceOrientation toOrientation = (UIInterfaceOrientation)[n.userInfo[@"toOrientation"] intValue];
  //..
}
Run Code Online (Sandbox Code Playgroud)

总结一下上面所看到的,用于处理通知的选择器采用一个可选的类型参数,NSNotification您可以存储您想要在userInfo字典中传递的任何信息.