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

查看:21
本文介绍了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

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天全站免登陆