2009-06-03 49 views
2

在我正在使用的iphone應用程序中,我使用自定義類來管理與主機的網絡通信。稱爲protocolClass的類是appDelegate中的ivar,並且是applicationDidFinishLaunching:方法中的alloc + init。如何將信息從appDelegate傳遞到UINavigationcontroller中的某個視圖控制器

現在,只要protocolClass從主機接收數據,它就會在其委託(我將其設置爲appDelegate)中調用protocolClassDidReceiveData:方法。然後我需要更新UINavigatorController中的其中一個customViewController中的數據。

我應該只是添加一個引用到customViewController我需要更新appDelegate?或者還有其他一些更有效的方法嗎?

如果我要保留對customViewcontroller的引用,那麼內存使用的分支是什麼?

在此先感謝。

回答

2

如果我認識你,你想在程序的某個不相關部分發生事件後更新視圖。

爲了減少代碼中依賴項的數量,我建議使用NSNotification而不是更緊密耦合的實例變量。通知是Cocoa概念,它允許您的代碼的一部分發出任意數量的偵聽器可註冊的類似事件的消息。

在你的情況是這樣的:

的AppDelegate頭:

extern NSString* kDataReceived; 

的AppDelegate實現:

NSString* kDataReceived = @"DataReceived"; 

- (void)protocolClassDidReceiveData:(NSData*)data { 
    [[NSNotificationCenter defaultCenter] postNotificationName:kDataReceived 
                 object:self 
                 userInfo:data]; 
} 
在一些感興趣的聽衆類的實現

(比如你的UIViewController) :

// register for the notification somewhere 
- (id)init 
{ 
    self = [super init]; 
    if (self != nil) { 
     [[NSNotificationCenter defaultCenter] addObserver:self 
               selector:@selector(dataReceivedNotification:) 
                name:kDataReceived 
                object:nil]; 
    } 
} 

// unregister 
- (void)dealloc 
{ 
    [[NSNotificationCenter defaultCenter] removeObserver:self]; 
} 

// receive the notification 
- (void)dataReceivedNotification:(NSNotification*)notification 
{ 
    NSData* data = [notification userInfo]; 
    // do something with data 
} 
+0

謝謝尼古拉,我會檢查通知中心。起初,我只是擔心使用通知中心的含義使用不必要的系統資源。 – Ben 2009-06-03 23:07:48

2

是的,通知是一個很好的方法。當一個模型想要更新控制器[即ViewController] - 通知是一個很好的方法。在我的情況下,我試圖發現使用SSDP(使用AsyncUdpSocket)的設備,並且我想在發現設備時更新/通知我的視圖控制器。由於這是異步的,當收到數據時,我使用了通知。下面是一個簡單的事情,我做的事:

在viewDidLoad中(我想替換init但是這並沒有爲我工作好) - 我登記我的ViewController一個通知如下:

*NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; 
    [nc addObserver:self 
      selector:@selector(foundController:) 
       name:@"DiscoveredController" 
      object:nil]; 

這裏在我的ViewController選擇:

// receive the notification 
- (void)foundController:(NSNotification *)note 
{ 
    self.controllerFoundStatus.text = @"We found a controller"; 
} 

在我的「模型」 [未在App代表 - 我創造,我用它來發現設備的新類「serviceSSDP」我所做的只是張貼通知如下:

[[NSNotificationCenter defaultCenter] postNotificationName:@"DiscoveredController" object:nil]; 

就是這樣。當我收到我的SSDP發現的正確響應時[通常是在AsyncUdpSocket的:

- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock 
    didReceiveData:(NSData *)data 
      withTag:(long)tag 
      fromHost:(NSString *)host 
       port:(UInt16)port 

]中。

相關問題