在swift中的viewcontrollers之间通过引用传递数组 [英] Pass array by reference between viewcontrollers in swift

查看:163
本文介绍了在swift中的viewcontrollers之间通过引用传递数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Objective-C时,我会将 NSMutableArray 从一个视图控制器 VC_A 传递给另一个 VC_B 只需将 VC_B 中的属性指定为

When using Objective-C I would pass a NSMutableArray from one view controller VC_A to another VC_B by simply assigning a property in VC_B as

VC_B.list = self.list

其中self为 VC_A

它允许在列表中的 VC_B 中完成更改当视图控制器被弹出导航堆栈时, VC_A 中的列表。

It allows the changes done in VC_B on the list to be seen in the list in VC_A when the view controller was say popped off the navigation stack.

但是在Swift中,由于数组是通过值传递,如上所述分配不起作用,所以我被困在如何解决这个问题。现在处理这个问题的正确方法是什么?

However in Swift as arrays are passed by value, assigning as above does not work so I am stuck how to solve this. What would be the correct way to handle this now?

推荐答案

您仍然可以通过将属性设为<$来在Swift中执行此操作c $ c> NSMutableArray ,和以前一样。如果您要求,基础类型仍然存在。但这在ObjC和Swift都是糟糕的设计。它会在远处创建怪异的动作(当事物神奇地改变不属于调用的值时)并且可能会破坏MVC(如果数据是持久的,它应该存在于模型中,而不是视图控制器中。)

You can still do this in Swift by making the property an NSMutableArray, just as before. Foundation types still exist if you ask for them. But this is bad design in both ObjC and Swift. It creates spooky action at a distance (when things magically change values that were not part of the call) and likely breaks MVC (if the data is persistent, it should live in the model, not in the view controllers).

Cocoa中有两种常见模式:将数据存储在模型中,或通过委托传递。

There are two common patterns in Cocoa: store the data in the model, or pass it via delegation.

如果这个数组表示某种持久状态(例如系统中的项列表),然后属于模型层,并且两个视图控制器都应该在那里读取和操作它,而不是通过彼此通信。 (参见模型 - 视图 - 控制器。)

If this array represents some kind of persistent state (such as a list of items in the system), then that belongs in the model layer, and both view controllers should read and manipulate it there rather than by communicating with each other. (See Model-View-Controller.)

如果此数组是一个瞬态数据(如作为从列表中选择的,然后调用VC应该将自己设置为接收VC的委托,并且当接收VC完成时,它应该将数据传递回其委托。 (参见代表和数据源。)

If this array is a transient piece of data (such as selections from a list), then the calling VC should set itself as the delegate to the receiving VC, and when the receiving VC finishes, it should pass the data back to its delegate. (See Delegates and Data Sources.)

这篇关于在swift中的viewcontrollers之间通过引用传递数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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