gpt4 book ai didi

swift - 在选项卡 View Controller 中跨 View Controller 访问 NSCache

转载 作者:搜寻专家 更新时间:2023-11-01 06:53:30 25 4
gpt4 key购买 nike

我想从我的应用程序中的多个位置访问 NSCache,因为我正在使用它来缓存来自 API 端点的图像。

例如下图中的 TableView 4 和 View Controller 6 使用相同的图像,所以我不想下载它们两次。

enter image description here

候选解:

  1. 单例

    class Cache {  

    private static var sharedCache: NSCache<AnyObject, AnyObject>?
    static public func getCache () -> NSCache<AnyObject, AnyObject> {

    if sharedCache == nil {
    self.sharedCache = NSCache()
    }
    return sharedCache!
    }
    }

似乎工作正常,但“单例很糟糕”所以......

  1. 将缓存存储在 TabViewController 中

这会将 View 与 View Controller 紧密耦合,因此...

  1. 以某种方式存储在 AppDelegate 中。但这不是和1一样吗?所以……

  2. 使用依赖注入(inject)。但是我们在选项卡 View Controller 中,所以这不是和 2 一样吗?

我不确定这里的策略是否正确,所以我想问是否有其他方法可以在这里使用。

我做了什么 使用 NSCache 创建了一个带有示例的应用程序,并探索了单例解决方案。我试过使用依赖注入(inject),但认为它没有意义。我查看了 Stack overflow 和文档,但对于这种特定情况,我没有发现任何潜在的解决方案。

我给出的内容一个最小的示例,其中包含我不满意的图表和经过测试的解决方案。

没有帮助的是说 NSCache 不正确或使用库的答案。我正在尝试使用 NSCache 进行我自己的学习,这不是家庭作业,我想解决此 App 结构中此问题的具体实例。

问题是什么如何避免在这种情况下使用单例,在选项卡 View Controller 中查看 Controller 。

最佳答案

首先。单例并不是天生就是坏的。它们会使您的代码难以测试,并且它们确实起到了依赖性磁铁的作用。

单例适用于作为工具的类,例如 NSFileManager 又名 FileManger,即不携带状态或数据的东西。

一个很好的替代方法是依赖注入(inject),但是对于 View Controller 和 Storyboard,它可能很难并且感觉很像样板。您最终在 prepareForSegue 中传递了所有内容。

一种可能的方法是声明一个协议(protocol)来描述一个类似缓存的接口(interface)。

protocol CacheProtocol: class {
func doCacheThing()
}

class Cache: CacheProtocol {
func doCacheThing() {
//
}
}

然后声明一个协议(protocol),所有希望使用这个缓存的东西都可以使用。

protocol CacheConsumer: class {
var cache: CacheProtocol? { get set }
func injectCache(to object: AnyObject)
}

extension CacheConsumer {
func injectCache(to object: AnyObject) {
if let consumer = object as? CacheConsumer {
consumer.cache = cache
}
}
}

最后在顶层创建这个缓存​​的具体实例。

/// Top most controller
class RootLevelViewController: UIViewController, CacheConsumer {
var cache: CacheProtocol? = Cache()

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
injectCache(to: segue.destination)
}

}

您可以在 prepareForSegue 中传递缓存。

或者您可以使用微妙的子类化来创建一致性。

class MyTabBarController: UITabBarController, CacheConsumer {
var cache: CacheProtocol?
}

或者你可以使用委托(delegate)方法让缓存对象广播下来。

extension RootLevelViewController: UITabBarControllerDelegate {
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
injectCache(to: viewController)
}
}

您现在拥有一个系统,其中任何 CacheConsumer 都可以使用缓存并将其向下传递给任何其他对象。

关于swift - 在选项卡 View Controller 中跨 View Controller 访问 NSCache,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55470792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com