IOS的消息传递机制,使用NSNotificationCenter进行通信,很实用

概述
在这个文档中,我们将讨论2个不相关的或者彼此之间不知道对方id的对象是如何通信的.所有的例子都是基于Objective-C的,这篇文章的关注点是Iphone开发.这个手册对那些在iphone开发和想要提高软件的易用性,扩展性的人将非常有用.


下面,我们将讨论具体的项目细节(http://www.hivestudio.cat/goldCube.zip),这个例子是一个小的OpenGL视图程序,你可以对金色正方体进行翻转.
图片



使用者可以用"Rotate X""Rotate Y"和"Rotate Z"进行操作.

当使用者点击"Rotate X"按钮,"ViewController"中的“button1()”函数将被调用.然后"ViewController"将通知“OpenGLView”,告诉他,用户要进行翻转物体,问题是“ViewController”并没有任何"OpenGLView"实例,唯一可行的方法是使用"NotificationCenter"进行通信.

下面是使用“NotificationCenter”对"ViewController"和"OpenGLView"进行通信的步骤:
1) 在OpenGLView中添加消息的观察者.
OpenGLView.m

- (void)prepareOpenGL
{
//1 -> Adding OpenGLView as an observer.
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(RotateX)
name:@"button1"//表示消息名称,发送跟接收双方都要一致
object:nil]
...

}
2)在"ViewController"中发送消息.
viewController.m

- (IBAction)button1:(id)pId;
{
//3 -> SENDING THE MESSAGE
[[NSNotificationCenter defaultCenter] postNotificationName:@"button1" object:self];//注意object属性
}

3)"OpenGLView"相应对此消息的对应方法.
OpenGLView.m

//2 à IMPLEMENTING THE METHOD
- (void) RotateX
{
NSLog(@"rotateX");
dAnlgeX=dAnlgeX+10;
}
这些步骤允许我们在"OpenGLView"和"viewController"之间传递消息

同时在dealloc方法,将observer从notification center中移除

- (void)dealloc

{

    [self setEmployees:nil];

    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];

    [nc removeObserver:self];

    [super dealloc];

}

原文地址:https://www.cnblogs.com/wengzilin/p/2398229.html