Iphone 如何发送带有Objective-C参数的通知?

Iphone 如何发送带有Objective-C参数的通知?,iphone,ios,notifications,Iphone,Ios,Notifications,我需要向应用程序(问题2)上的所有UIViewController发送通知@“WillAnimateRotationInterfaceOrientation”,通知参数为toInterfaceOrientation和duration(问题1)。如何为此编写代码 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willAnimateRotationToInterfaceOrientat

我需要向应用程序(问题2)上的所有
UIViewController
发送通知
@“WillAnimateRotationInterfaceOrientation”
,通知参数为
toInterfaceOrientation
duration
问题1)。如何为此编写代码

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

[[NSNotificationCenter defaultCenter] 
  postNotificationName:@"willAnimateRotationToInterfaceOrientation"
                object:self];

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

例如:

你可以像这样发布通知

NSDictionary * userInfo = @{ @"toOrientation" : @(toOrientation) };
[[NSNotificationCenter defaultCenter] postNotificationName:@"willAnimateRotationToInterfaceOrientation" object:nil userInfo:userInfo];
然后通过执行以下操作检索您传递的信息:

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

综上所述,用于处理通知的选择器采用一个可选参数,类型为
NSNotification
,您可以将想要传递的任何信息存储在
userInfo
字典中。

您使调用方法更简单,这需要更少的参数,并为您完成复杂的调用

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

- (void)doStuff {
  [self willAnimateRotationToInterfaceOrientation:someOrientation
                                    toOrientation:someOtherOrientation
                                         duration:1];
}


不过,你不应该自己调用
WillAnimateRotationInterfaceOrientation:
。相反,创建一个名为form的方法,该方法包含您希望在旋转和其他时间激活的代码。

这与您认为的方式不同。通知消息调用有一个可选参数,它是
NSNotification
对象:

-(void)myNotificationSelector:(NSNotification*)note;
-(void)myNotificationSelector;

通知对象有一个属性,
userInfo
,它是一个可用于传递相关信息的字典。但您不能注册任意选择器以供通知中心调用。通过使用
-postNotificationName:object:userInfo:
而不是
-postNotificationName:object:
传递带有通知的词典;
userInfo
参数只是您创建的一个
NSDictionary

但是如何使用
userInfo
传递参数?相关问题:谢谢,但是是否可以向应用程序的所有(或所有可见的)
UIViewController
发送通知?前提是它们都注册了该通知。请注意,如果您通过调用
[[UIDevice currentDevice]BegingeratingDeviceOrientationNotifications]
请求通知,则有一个现有通知,
UIDeviceOrientationIDChangeNotification
(但您仍然必须为其注册每个视图控制器)。当调用
NSNotificationCenter-addObserver:selector:name:object:
时,它将被发送到所有传递指向
object
参数的指针的对象。事实上,您只需在
addObserver::
中通过
nil
;然后,即使
postNotificationName:object:
对于
object
具有非
nil
值,您也会收到所有通知。请参阅Gabriele的代码。您需要将这两个值推入
NSNumber
s,因为
NSDictionary
只能保存对象值。代码有以下错误:1。程序中出现意外的“@”。2.“UIInterfaceOrientation”(也称为“enum UIInterfaceOrientation”)类型的集合元素不是Objective-C对象。您需要在括号之间换行
toOrientation
。固定的。