iphone - 添加观察者时是否需要接收NSNotification?

标签 iphone objective-c cocoa-touch ipad

事情是这样的..

每次我看到与网络相关的 iphone - ipad dev 的示例时,我都会看到每次 Controller 注册自身以接收通知时,回调方法如下:

-(void)mymethod:(NSNotification *)notification {
    //Bla Bla
}

与按钮操作相同..总是喜欢:

- (void)actionmethod:(id)sender {
     //Bla Bla
}

我只是做了一些测试,无论有没有参数,该方法都会被调用。 这真的有必要吗?出于什么原因?

谢谢你!!!

最佳答案

来自NSNotificationCenter doc :

notificationSelector
Selector that specifies the message the receiver sends notificationObserver to notify it of the notification posting. The method specified by notificationSelector must have one and only one argument (an instance of NSNotification).

[强调我的。]

您必须提供具有正确签名的选择器;如果您不这样做,它可能会起作用,但它可能会在您不希望它工作时停止工作。

您可能想要获取通知的原因是,您可以以 userInfo 字典的形式传递信息,您可以在自己使用 notificationWithName:object:userInfo: 发布通知时指定该字典。 。调用方法时可以忽略参数,但参数必须存在于方法签名中。

对于按钮及其操作,docs假设您可以拥有三个签名之一*:

the UIKit framework allows three different forms of action selector:
- (void)action
- (void)action:(id)sender
- (void)action:(id)sender forEvent:(UIEvent *)event

IBAction 返回类型等同于 void(没有返回值),只不过它出现在 header 的方法中可以让 Interface Builder 知道方法旨在作为一个操作,以便您可以连接控件。

想要获取按钮(或其他控件)的原因与通知类似。如果您的界面中有许多按钮,其中一些按钮(例如在表格 View 中)连接到相同的操作,您可能需要通过按下的按钮的标识来区分您执行的确切操作。


*:为了完整起见,我想提一下,Mac 上的情况并非如此;其中,操作方法必须采用以下形式:- (IBAction)action:(id)sender

关于iphone - 添加观察者时是否需要接收NSNotification?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5630754/

相关文章:

ios - 如何为不同的 iOS 显示器计算正确的图像尺寸?

ios - 我该如何修复或解决此 tableView textField 自动布局故障?

ios - 元组属性的自定义 setter (Swift)

iphone - 获取 MKMapView 的边界

iphone - iOS - 如何在 UITableView 上显示 UIImagePicker?

ios - 使用ARKit作为“奖励”的普通应用程序?

ios - 相机预览黑色

iphone - 当 iPhone 在 iOS5 上被锁定时,如何防止应用程序被发送终止信号?

ios - 如何获取视频回复列表 YouTube API Objective C

ios - PhoneGap 3.3.0 在 URLforFilesystemPath : selector 上崩溃