是的,通知是一個很好的方法。當一個模型想要更新控制器[即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
]中。
謝謝尼古拉,我會檢查通知中心。起初,我只是擔心使用通知中心的含義使用不必要的系統資源。 – Ben 2009-06-03 23:07:48