ios - 如何在多个 View Controller 上使用数组?

标签 ios swift firebase uinavigationcontroller firebase-realtime-database

我一直在玩弄很多涉及数组和 ScrollView 的东西。我主要停留在 View Controller 的范围内,所以通常我会从 firebase 获取数据,将其添加到数组,然后将其发送到 tableview 或 collectionview。我现在要做的实际上是在 View Controller (或同一 View Controller 的多个副本)之间导航,并将数组项应用于每个 View Controller 。

例如,我希望能够从 firebase 抓取一些照片,将它们放入 url 字符串数组或其他任何内容中。然后我想在 View Controller 的背景上放一张照片。然后当我按下结束按钮时,它会导航到下一个 View Controller 并将下一张照片作为背景,等等。

我知道可能有多种方法可以做到这一点,我想知道最有效的方法是什么?我是否只是将一个数组放在 Global 类中并从所有 View Controller 访问它?或者我只是将数组保存在第一个 View Controller 中,然后在导航时不断将它发送到下一个 View Controller ?这里还会有很多项目、对象和数组,所以这就是我追求效率的原因。提前感谢任何能够提供帮助的人,我希望我解释得足够好!

最佳答案

这是一种从struct中添加和检索String值的非常简单的方法,在这里您将图像url字符串作为值保存在字典中,它是键将成为 ViewController 名称。

struct SavedData {
    static private var imagesDictionary: [String: String] = [:]

    static func image(for viewController: UIViewController) -> String? {
        return imagesDictionary["\(type(of: viewController))"]
    }

    static func add(image name: String, for viewController: UIViewController) {
        self.imagesDictionary["\(type(of: viewController))"] = name
    }
}

保存值非常简单,如果您将数据保存在 viewController 中,并且您希望为该 viewController 保存特定图像,您可以使用 self

SavedData.add(image: "img1.png", for: self)

如果您想为不同的 viewController 保存图像,请按此操作。

SavedData.add(image: "img2.png", for: SecondViewController())

获取图像也很简单,你应该在你想要分配图像的 viewController 中调用这个方法。

let savedImage = SavedData.image(for: self)
print(savedImage!)

关于ios - 如何在多个 View Controller 上使用数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40815991/

相关文章:

swift - NotificationCenter 观察员没有收到帖子

ios - 如何通过Arkit人脸跟踪获取3D位置数据?

javascript - 带有 Firebase/Firestore 后端的双向无限滚动

ios - inAPP购买测试流程

ios - 如何使用设备运动更新将 SCNNode 固定在特定位置?

ios - UIDocument loadFromContents 应该返回一个 NSFileWrapper;改为返回 NSConcreteData

firebase - 错误 : no entity to update: app - Firestore Cloud Function

java - Android firebase onStart 和 onStop 解释

iphone - 配置文件中的新 UDID

iphone - 如何在 iPad 中自动旋转期间重新排列 View