【发布时间】:2010-12-14 11:01:08
【问题描述】:
我想知道在 iPhone 开发中应用程序流程的最佳实践是什么。
你如何在 ViewController 之间传递消息?
你用单例吗?在视图之间传递它,或者您是否有一个用于管理流程的应用程序的主控制器?
谢谢。
【问题讨论】:
我想知道在 iPhone 开发中应用程序流程的最佳实践是什么。
你如何在 ViewController 之间传递消息?
你用单例吗?在视图之间传递它,或者您是否有一个用于管理流程的应用程序的主控制器?
谢谢。
【问题讨论】:
NSNotification 类有点重量级,但符合您描述的用法。它的工作方式是您的各种NSViewControllers 注册NSNotificationCenter 以接收他们感兴趣的事件
Cocoa Touch 处理路由,包括为您提供一个类似单例的“默认通知中心”。请参阅 Apple 的 notification guide 了解更多信息。
【讨论】:
我使用NSNotificationCenter,这对于这种工作来说太棒了。将其视为广播消息的一种简单方法。
您想要接收消息的每个 ViewController 都会通知默认的 NSNotificationCenter 它想要侦听您的消息,并且当您发送消息时,每个附加侦听器中的委托都会运行。例如,
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);
}
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
【讨论】: