iPhone SDK如何在视图控制器之间传递信息

4

我想知道iPhone开发中应用程序流程的最佳实践。


您如何在视图控制器之间传递消息?

您使用单例模式吗?将其在视图之间传递还是有一个主控制器来管理流程?

谢谢。

2个回答

13
我使用NSNotificationCenter,这对于这种工作非常棒。可以将其视为广播消息的简单方式。
每个你想要接收消息的ViewController都会通知默认的NSNotificationCenter它想要监听你的消息,当你发送它时,每个附加侦听器中的委托都会运行。例如,

ViewController.m

NSNotificationCenter *note = [NSNotificationCenter defaultCenter];
[note addObserver:self selector:@selector(eventDidFire:) name:@"ILikeTurtlesEvent" object:nil];

/* ... */

- (void) eventDidFire:(NSNotification *)note {
    id obj = [note object];
    NSLog(@"First one got %@", obj);
}

ViewControllerB.m

NSNotificationCenter *note = [NSNotificationCenter defaultCenter];
[note addObserver:self selector:@selector(awesomeSauce:) name:@"ILikeTurtlesEvent" object:nil];
[note postNotificationName:@"ILikeTurtlesEvent" object:@"StackOverflow"];

/* ... */

- (void) awesomeSauce:(NSNotification *)note {
    id obj = [note object];
    NSLog(@"Second one got %@", obj);
}

将会产生以下结果(顺序取决于哪个ViewController先注册):

First one got StackOverflow
Second one got StackOverflow

0

NSNotification 类有点繁重,但适合您所描述的用法。它的工作方式是,您的各种 NSViewControllerNSNotificationCenter 注册以接收它们感兴趣的事件。

Cocoa Touch 处理路由,包括为您提供类似单例的“默认通知中心”。更多信息请参见 Apple 的 notification guide


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接