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];
}
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的IOS的消息传递机制,使用NSNotificationCenter进行通信,很实用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: zz STL 优先队列
- 下一篇: 重磅推荐12款jQuery编写的选择器