简体   繁体   English

如何在两个视图控制器之间传递字符串或数据对象?

[英]How do I pass a string or data object between two view controllers?

In my last question I asked how to best send a string from one view controller to another, both which were on a navigation stack: Pass string from tableviewcontroller to viewcontroller in navigation stack 在我的最后一个问题中,我问如何最好地将字符串从一个视图控制器发送到另一个视图控制器,这两个控件都在导航堆栈中:将字符串从tableviewcontroller传递到导航堆栈中的viewcontroller

However I just realised I can either pass the path to the file in the app's document's folder as the first (the table view) has already accessed the data in the file should I pass viewcontroller the data to the pushed VC? 但是我只是意识到我可以将路径传递到应用程序文档文件夹中的文件,因为第一个(表视图)已经访问了文件中的数据,是否应该将viewcontroller数据传递给推送的VC?

Passing a reference would be less overhead than reinitializing a fresh object in the child view controller. 与在子视图控制器中重新初始化一个新对象相比,传递引用将减少开销。

Set up a retain property in the child view controller for the NSString instance. 在子视图控制器中为NSString实例设置一个retain属性

In the parent view controller, instantiate the child view controller and set its string property equal to the string you want to pass it: 在父视图控制器中,实例化子视图控制器,并将其string属性设置为等于您要传递给它的字符串:

childViewController.myStringProperty = parentViewControllerString;

As this increments the retain count of the string, you're not recreating the object, just keeping a reference to it. 由于这会增加字符串的retain计数,因此您无需重新创建对象,而只需保留对其的引用即可。

You could instead retain an NSData instance, if you wanted. 如果需要,可以改为保留NSData实例。 This would be less of a hit than recreating it in the child vc 比在子vc中重新创建命中命中率要小

My first thought is that you should pass say the NSData object to the pushed view controller. 我的第一个想法是您应该将NSData对象传递给推送的视图控制器。 If it's not too large it will save you from loading it again. 如果不是太大,则可以避免再次加载。

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

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