什么是视图控制器之间通信的最佳方式? [英] What's the best way to communicate between view controllers?

查看:81
本文介绍了什么是视图控制器之间通信的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为一个新的目标c,可可和iPhone开发,我有一个强烈的愿望,以充分利用语言和框架。

Being new to objective-c, cocoa, and iPhone dev in general, I have a strong desire to get the most out of the language and the frameworks.

我使用的资源之一是斯坦福的CS193P类注意到他们已经留在网上。它包括演讲笔记,作业和示例代码,由于该课程是由苹果开发商提供的,我绝对认为它是从马的嘴。

One of the resources I'm using is Stanford's CS193P class notes that they have left on the web. It includes lecture notes, assignments and sample code, and since the course was given by Apple dev's, I definitely consider it to be "from the horse's mouth".



http://www.stanford。 edu / class / cs193p / cgi-bin / index.php

讲义08与一个赋值建立一个基于UINavigationController的应用程序相关,该应用程序有多个UIViewControllers到UINavigationController堆栈。这就是UINavigationController的工作原理。这是合乎逻辑的。但是,幻灯片中有一些严重警告,说明您的UIViewControllers之间的通信。

Lecture 08 is related to an assignment to build a UINavigationController based app that has multiple UIViewControllers pushed onto the UINavigationController stack. That's how the UINavigationController works. That's logical. However, there are some stern warnings in the slide about communicating between your UIViewControllers.

我要引用这张严肃的幻灯片:

http://cs193p.stanford.edu/downloads/08-NavigationTabBarControllers.pdf

I'm going to quote from this serious of slides:
http://cs193p.stanford.edu/downloads/08-NavigationTabBarControllers.pdf

第16/51页:


h1>


  • 全局变量或单例


    • 这包括您的应用程式委托

How Not To Share Data

  • Global Variables or singletons
    • This includes your application delegate

  • 更难调试&测试



<我下来了。不要盲目地抛出所有用于在viewcontroller之间进行通信的方法,以及在app委托方法中引用viewcontroller实例。

Ok. I'm down with that. Don't blindly toss all your methods that will be used for communicating between the viewcontroller into your app delegate and reference the viewcontroller instances in the app delegate methods. Fair 'nuff.

稍后,我们会看到这张幻灯片告诉我们应该做什么。

A bit further on, we get this slide telling us what we should do.

第18/51页:


数据流最佳实践


$ b b

  • 确定需要传达的信息

  • 定义输入参数



    • 定义一个通用的

Best Practices for Data Flow

  • Figure out exactly what needs to be communicated
  • Define input parameters for your view controller
  • For communicating back up the hierarchy, use loose coupling
    • Define a generic interface for observers (like delegation)

这张幻灯片后面是一个似乎是一个占位符幻灯片,讲师然后显然演示了使用UIImagePickerController的示例的最佳做法。我希望视频可用! :(

This slide is then followed by what appears to be a place holder slide where the lecturer then apparently demonstrates the best practices using an example with the UIImagePickerController. I wish the videos were available! :(

好吧,恐怕我的objc-fu不是那么强了,我也有点困惑了上面的最后一行我已经做了我公平的分享这个和我发现似乎是一个体面的文章,谈论观察/通知技术的各种方法:

http://cocoawithlove.com/2008/06/five-approaches-to-listening-observing。 html

Ok, so... I'm afraid my objc-fu is not so strong. I'm also a bit confused by the final line in the above quote. I've been doing my fair share of googling about this and I found what appears to be a decent article talking about the various methods of Observing/Notification techniques:
http://cocoawithlove.com/2008/06/five-approaches-to-listening-observing.html

方法#5甚至表示委托为方法!除了....对象一次只能设置一个委托,所以当我有多个viewcontroller通信,我要做什么?

Method #5 even indicates delegates as an method! Except.... objects can only set one delegate at a time. So when I have multiple viewcontroller communication, what am I to do?

好吧,这是设置帮派,我知道我可以很容易地做我的通信方法在应用程序委托通过引用的多视图控制器

Ok, that's the set up gang. I know I can easily do my communication methods in the app delegate by reference's the multiple viewcontroller instances in my appdelegate but I want to do this sort of thing the right way.

请通过回答帮助我做正确的事来帮助我做正确的事情。以下问题:

Please help me "do the right thing" by answering the following questions:


  1. 当我试图在UINavigationController堆栈上推送一个新的viewcontroller时, who 做这个推。 我的代码中的哪个类/文件是正确的地方?

  2. 当我想在我的一个UIViewController中影响某些数据(iVar的值)当我在一个不同的 UIViewController,什么是正确的方式这样做?

  3. 给我们一次只能有一个代理集一个对象,当讲师说为观察者定义一个通用接口(如委派)时,实现会是什么样子。 如果可能,一个伪代码示例将非常有用。

  1. When I am trying to push a new viewcontroller on the UINavigationController stack, who should be doing this push. Which class/file in my code is the correct place?
  2. When I want to affect some piece of data (value of an iVar) in one of my UIViewControllers when I am in a different UIViewController, what is the "right" way to do this?
  3. Give that we can only have one delegate set at a time in an object, what would the implementation look like for when the lecturer says "Define a generic interface for observers (like delegation)". A pseudocode example would be awfully helpful here if possible.


推荐答案

很高兴看到你正在做这项研究,看起来很关心学习如何做正确,而不是只是一起黑客。

These are good questions, and its great to see that you're doing this research and seem concerned with learning how to "do it right" instead of just hacking it together.

首先,我同意以前的答案,重点放在在适当的情况下(根据MVC设计模式)将数据放在模型对象中的重要性。

First, I agree with the previous answers which focus on the importance of putting data in model objects when appropriate (per the MVC design pattern). Usually you want to avoid putting state information inside a controller, unless it's strictly "presentation" data.

第二 ,参见斯坦福演讲的第10页,了解如何以编程方式将控制器推到导航控制器上的示例。有关如何使用Interface Builder直观地执行此操作的示例,请查看本教程

第三 如果您在依赖注入设计模式的上下文中考虑它们,那么在斯坦福演讲中提到的最佳实践更容易理解。简而言之,这意味着您的控制器不应该查找它需要完成其工作的对象(例如,引用一个全局变量)。相反,你应该总是注入这些依赖到控制器(即,通过方法传递它需要的对象)。

Third, and perhaps most importantly, note that the "best practices" mentioned in the Stanford presentation are much easier to understand if you think about them in the context of the "dependency injection" design pattern. In a nutshell, this means that your controller shouldn't "look up" the objects it needs to do its job (e.g., reference a global variable). Instead, you should always "inject" those dependencies into the controller (i.e., pass in the objects it needs via methods).

如果你遵循依赖注入模式,你的控制器将是模块化和可重用的。如果你想到斯坦福大学的演讲者来自哪里(即,作为苹果员工,他们的工作是建立类,可以很容易地重复使用),可重用性和模块化是高优先级。他们提到的用于共享数据的所有最佳实践都是依赖注入的一部分。

If you follow the dependency injection pattern, your controller will be modular and reusable. And if you think about where the Stanford presenters are coming from (i.e., as Apple employees their job is to build classes that can easily be reused), reusability and modularity are high priorities. All of the best practices they mention for sharing data are part of dependency injection.

这是我的回答的要点。

That's the gist of my response. I'll include an example of using the dependency injection pattern with a controller below in case it's helpful.

使用视图控制器使用依赖注入的示例

Example of Using Dependency Injection with a View Controller

假设您正在建立一个列出多本书的画面。用户可以选择他/她想要购买的书,然后点击结帐按钮去到结帐屏幕。

Let's say you're building a screen in which several books are listed. The user can pick books he/she wants to buy, and then tap a "checkout" button to go to the checkout screen.

要创建这个,你可以创建一个BookPickerViewController类来控制和显示GUI /视图对象。它将在哪里获得所有的图书数据?让我们说它取决于一个BookWarehouse对象。所以现在你的控制器基本上是介于模型对象(BookWarehouse)和GUI /视图对象之间的数据。换句话说,BookPickerViewController DEPENDS对BookWarehouse对象。

To build this, you might create a BookPickerViewController class that controlls and displays the GUI/view objects. Where will it get all the book data? Let's say it depends on a BookWarehouse object for that. So now your controller is basically brokering data between a model object (BookWarehouse) and the GUI/view objects. In other words, BookPickerViewController DEPENDS on the BookWarehouse object.

不要这样做:

@implementation BookPickerViewController

-(void) doSomething {
   // I need to do something with the BookWarehouse so I'm going to look it up
   // using the BookWarehouse class method (comparable to a global variable)
   BookWarehouse *warehouse = [BookWarehouse getSingleton];
   ...
}

相反, :

@implementation BookPickerViewController

-(void) initWithWarehouse: (BookWarehouse*)warehouse {
   // myBookWarehouse is an instance variable
   myBookWarehouse = warehouse;
   [myBookWarehouse retain];
}

-(void) doSomething {
   // I need to do something with the BookWarehouse object which was 
   // injected for me
   [myBookWarehouse listBooks];
   ...
}

当苹果公司谈论使用代理模式来沟通备份层次结构,他们仍在谈论依赖注入。在这个例子中,BookPickerViewController在用户选择他/她的书籍并准备好签出后应该做什么?嗯,这不是真正的工作。它应该DELEGATE工作到其他对象,这意味着它DEPENDS对另一个对象。所以我们可以修改我们的BookPickerViewController init方法如下:

When the Apple guys are talking about using the delegation pattern to "communicate back up the hierarchy," they're still talking about dependency injection. In this example, what should the BookPickerViewController do once the user has picked his/her books and is ready to check out? Well, that's not really its job. It should DELEGATE that work to some other object, which means that it DEPENDS on another object. So we might modify our BookPickerViewController init method as follows:

@implementation BookPickerViewController

-(void) initWithWarehouse:    (BookWarehouse*)warehouse 
        andCheckoutController:(CheckoutController*)checkoutController 
{
   myBookWarehouse = warehouse;
   myCheckoutController = checkoutController;
}

-(void) handleCheckout {
   // We've collected the user's book picks in a "bookPicks" variable
   [myCheckoutController handleCheckout: bookPicks];
   ...
}

可以给我你的BookPickerViewController类(和相关的GUI /视图对象),我可以很容易地使用它在我自己的应用程序,假设BookWarehouse和CheckoutController是通用接口(即协议),我可以实现:

The net result of all this is that you can give me your BookPickerViewController class (and related GUI/view objects) and I can easily use it in my own application, assuming BookWarehouse and CheckoutController are generic interfaces (i.e., protocols) that I can implement:

@interface MyBookWarehouse : NSObject <BookWarehouse> { ... } @end
@implementation MyBookWarehouse { ... } @end

@interface MyCheckoutController : NSObject <CheckoutController> { ... } @end
@implementation MyCheckoutController { ... } @end

...

-(void) applicationDidFinishLoading {
   MyBookWarehouse *myWarehouse = [[MyBookWarehouse alloc]init];
   MyCheckoutController *myCheckout = [[MyCheckoutController alloc]init];

   BookPickerViewController *bookPicker = [[BookPickerViewController alloc] 
                                         initWithWarehouse:myWarehouse 
                                         andCheckoutController:myCheckout];
   ...
   [window addSubview:[bookPicker view]];
   [window makeKeyAndVisible];
}



最后,您的BookPickerController不仅可重用,而且更容易测试。

Finally, not only is your BookPickerController reusable but also easier to test.

-(void) testBookPickerController {
   MockBookWarehouse *myWarehouse = [[MockBookWarehouse alloc]init];
   MockCheckoutController *myCheckout = [[MockCheckoutController alloc]init];

   BookPickerViewController *bookPicker = [[BookPickerViewController alloc] initWithWarehouse:myWarehouse andCheckoutController:myCheckout];
   ...
   [bookPicker handleCheckout];

   // Do stuff to verify that BookPickerViewController correctly called
   // MockCheckoutController's handleCheckout: method and passed it a valid
   // list of books
   ...
}

这篇关于什么是视图控制器之间通信的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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