iPhone sdk在视图控制器之间传递消息

lne*_*nel 4 iphone uiviewcontroller

我想知道iPhone开发中应用程序流程的最佳实践是什么.
如何在ViewControllers之间传递消息?你使用单身人士吗?在视图之间传递它还是有管理流程的应用程序的主控制器?

谢谢.

Jed*_*ith 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);
}
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

将产生(以任何顺序取决于哪个ViewController首先注册):

First one got StackOverflow
Second one got StackOverflow
Run Code Online (Sandbox Code Playgroud)