本文介绍了在Cocoa应用程序中共享数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了如何正确执行此操作,但是我不相信自己找到了答案。这是我的设置:



NSWindowController加载2个不同的NSViewControllers(一次只显示一个)。当我将文件拖放到已加载的NSViewController的视图上时,我想保存该文件的路径。我可以得到所有这些,但是现在我想做的就是当我交换到另一个NSViewController时,我想将此文件路径传递给新的NSViewController。



我想出的唯一解决方案是将通知从我的NSViewController发布到NSWindowController,然后使用此数据初始化第二个NSViewController,但这似乎很麻烦。有没有一种方法可以将数据保存为全局实体,然后再从第二个NSViewController中访问它?彼此交换。



任何见识都会受到赞赏。



更新:我只是要更改应用程序,以便两个视图控制器始终都在内存中。这样,我可以按照他人的建议进行操作,并使用KVO或其他方法。

解决方案

视图控制器用于控制模型的视图对象。因此,您的每个视图控制器都必须从某个基础模型对象获取数据,而这些基础模型对象在您的情况下可能是相同的。如果没有,建议您将应用程序重新设计为MVC模式。



创建视图控制器时,可以设置属性,并将文件名存储为属性之一。如果您的模型对象是KVO兼容的,您甚至可以让每个视图控制器观察模型对象的文件名属性,并对更改进行响应。


I have searched for how to correctly do this, but I don't believe I have found my answer. This is my setup:

NSWindowController loads in 2 different NSViewControllers (only one is displayed at a time). When I drop a file onto the NSViewController's view that is loaded, I want to save the path of that file. I can get all of this, but what I want to be able to do now is when I swap to my other NSViewController, I want to pass on this file path to the new NSViewController.

The only solution I have come up with is to post a notification from my NSViewController to the NSWindowController and then initialize the 2nd NSViewController with this data, but it seems rather convoluted. Is there a way that I can just save the data somewhere as a global entity and then access it later from my 2nd NSViewController?

NOTE: The NSViewControllers are being released after they are swapped with the other.

Any insight would be appreciated.

UPDATE: I'm just going to change the application so that both view controllers are in memory at all times. This way I can do as others have suggested and use KVO or other methods.

解决方案

View controllers are meant for controlling views of model objects. So each of your view controllers must be getting their data from some underlying model object which presumably in your case is the same one. If you don't have that, I suggest you re-engineer your application to the MVC pattern.

When you create your view controllers you can set the representedObject property and store the file name as one of its properties. If your model object is KVO compliant you can even have each view controller observe the file name property of the model object and react to changes when they happen.

这篇关于在Cocoa应用程序中共享数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-08 16:26