iPhone sdk在视图控制器之间传递消息 [英] iPhone sdk pass messages between view controllers

查看:98
本文介绍了iPhone sdk在视图控制器之间传递消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

如何在ViewControllers之间传递消息?
你使用单身人士吗?在视图之间传递它还是有管理流程的应用程序的主控制器?

I was wondering what is the best practice for an application flow in iPhone development.
How do you pass messages between ViewControllers? Do you use singletons? pass it between views or do you have a main controller for the application that manage the flow?

谢谢。

推荐答案

我使用 NSNotificationCenter ,这对于这类工作来说非常棒。将其视为一种简单的广播消息方式。

I use NSNotificationCenter, which is fantastic for this kind of work. Think of it as an easy way to broadcast messages.

您希望接收消息的每个ViewController都会通知默认的NSNotificationCenter它想要收听您的消息,当您发送它,每个连接的监听器中的委托都运行。例如,

Each ViewController you want to receive the message informs the default NSNotificationCenter that it wants to listen for your message, and when you send it, the delegate in every attached listener is run. For example,

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



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首先注册):

Would produce (in either order depending on which ViewController registers first):

First one got StackOverflow
Second one got StackOverflow

这篇关于iPhone sdk在视图控制器之间传递消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆