简体   繁体   English

在视图控制器之间传递非静态对象

[英]Passing Non-Static Objects Between View Controllers

I'm a newb to iphone development and objective c, but hoping some folks smarter than me can lend a hand. 我是iPhone开发和目标C的新手,但希望有些比我聪明的人可以伸出援手。 Here's my problem: 这是我的问题:

I have a view based app with about 7 different view controllers. 我有一个基于视图的应用程序,带有大约7个不同的视图控制器。 The user navigates via a bottom tab bar. 用户通过底部的标签栏导航。 I have the users entering data in the first view controller to an object named "copies". 我让用户在第一个视图控制器中向名为“副本”的对象输入数据。 I need to get the copies value to another controller so it can be used for calculations. 我需要将副本值传递到另一个控制器,以便可以将其用于计算。 This needs to be done for many objects in the apps other controllers too. 对于其他控制器中的应用程序中的许多对象,也需要完成此操作。

Example: 例:

User enters Copies value in 1st view controller. 用户在第一视图控制器中输入份数值。
User enters Price value in 6th view controller. 用户在第六个视图控制器中输入价格值。

7th view controller calculates copies x price = grand total 第7个视图控制器计算份数x价格=总计

In my research I worked out the singleton method, but that seems limited to static data. 在我的研究中,我制定了单例方法,但这似乎仅限于静态数据。

What's the best way to ensure that another view controller can access an object the user has filled in? 确保另一个视图控制器可以访问用户已填充的对象的最佳方法是什么? I'm trying to avoid going a SQLite route currently. 我正在尝试避免当前使用SQLite路由。 I want to stick to something basic and work my way up in complexity. 我想坚持一些基本的原则,并努力提高复杂性。 Does anyone have any sample code I can review? 有人有我可以审查的示例代码吗? It really helps to see how others have tackled this before. 看看其他人以前如何解决这个问题确实有帮助。

Thanks in advance! 提前致谢!

If I've understood you correctly there is just one copies value and one price value in the whole app. 如果我对您的理解正确,则整个应用程序中只有一个copies价值和一个price价值。 If that is the case... 如果是这样的话...

There are many ways to do this. 有很多方法可以做到这一点。 Easiest way (perhaps): you could make a Singleton object of a class that you define that has copies and price as properties. 最简单的方法(也许):您可以创建自己定义的类的Singleton对象,该类具有copiesprice作为属性。 Singleton in Objective-C is here , and you would define your properties within the Singleton class. 在Objective-C中的Singleton在此处 ,您将在Singleton类中定义属性。 Then you would just call its shared instance and use the values on that. 然后,您只需调用其共享实例并在其上使用值即可。 So your code would look like this: 因此,您的代码如下所示:

   [ThatCrazySingleton sharedInstance].copies = 5;

for writing. 用于写作。

Hope this is what you're looking for. 希望这是您想要的。

If you don't want to use a Singleton, at some point one of the UIViewControllers would need to send a message to the others with the copies and price values (hopefully wrapped up ["encapsulated"] in an object). 如果您不想使用Singleton,则在某个时候,其中一个UIViewControllers需要向其他消息发送带有副本和价格值的消息(希望在对象中包含[“ encapsulated”])。 This means that you have to get a reference to the other View controllers, which you can always do by going through the hierarchy. 这意味着您必须获得对其他View控制器的引用,您始终可以通过遍历层次结构来进行引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM