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];

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM