2009-06-03 48 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 

]中。

相关问题