斯威夫特的单身人士

时间:2014-11-04 18:15:47

标签: swift singleton

我一直在努力实现一个单例用作照片的缓存,我从网络上传到我的iOS应用程序。我在下面的代码中附加了三个变体。我试图让变量2工作,但它导致编译器错误,我不明白,并希望得到帮助我做错了什么。变体1执行缓存但我不喜欢使用全局变量。变体3没有进行实际的缓存,我相信这是因为我在var ic = ....的赋值中得到了一个副本,这是正确的吗?

非常感谢任何反馈和见解。

谢谢, 兹维

import UIKit

private var imageCache: [String: UIImage?] = [String : UIImage?]()

class ImageCache {
    class var imageCache: [String : UIImage?] {
        struct Static {
            static var instance: [String : UIImage?]?
            static var token: dispatch_once_t = 0
        }

        dispatch_once(&Static.token) {
            Static.instance = [String : UIImage?]()
        }
        return Static.instance!
    }
}

class ViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        imageView.image = UIImage(data: NSData(contentsOfURL: NSURL(string: "http://images.apple.com/v/iphone-5s/gallery/a/images/download/photo_1.jpg")!)!)

        //variant 1 - this code is working
        imageCache["photo_1"] = imageView.image
        NSLog(imageCache["photo_1"] == nil ? "no good" : "cached")

        //variant 2 - causing a compiler error on next line: '@lvalue $T7' is not identical to '(String, UIImage?)'
        //ImageCache.imageCache["photo_1"] = imageView.image
        //NSLog(ImageCache.imageCache["photo_1"] == nil ? "no good" : "cached")

        //variant 3 - not doing the caching
        //var ic = ImageCache.imageCache
        //ic["photo_1)"] = imageView.image
        //NSLog(ImageCache.imageCache["photo_1"] == nil ? "no good" : "cached")
    }
}

4 个答案:

答案 0 :(得分:28)

标准单例模式是:

final class Manager {
    static let shared = Manager()

    private init() { ... }

    func foo() { ... }
}

你可以像这样使用它:

Manager.shared.foo()

相信appzYourLife指出应该声明它final以确保它不会被意外地子类化,以及使用private访问修饰符来初始化器,以确保你不会意外地实例化另一个实例。请参阅https://stackoverflow.com/a/38793747/1271826

因此,返回到图像缓存问题,您将使用此单例模式:

final class ImageCache {

    static let shared = ImageCache()

    /// Private image cache.

    private var cache = [String: UIImage]()

    // Note, this is `private` to avoid subclassing this; singletons shouldn't be subclassed.

    private init() { }

    /// Subscript operator to retrieve and update cache

    subscript(key: String) -> UIImage? {
        get {
            return cache[key]
        }

        set (newValue) {
            cache[key] = newValue
        }
    }
}

然后你可以:

ImageCache.shared["photo1"] = image
let image2 = ImageCache.shared["photo2"])

let cache = ImageCache.shared
cache["photo1"] = image
let image2 = cache["photo2"]

在上面展示了一个简单的单例缓存实现之后,我们应该注意到你可能希望(a)使用NSCache使其线程安全; (b)回应记忆压力。因此,实际的实现类似于Swift 3中的以下内容:

final class ImageCache: NSCache<AnyObject, UIImage> {

    static let shared = ImageCache()

    /// Observer for `UIApplicationDidReceiveMemoryWarningNotification`.

    private var memoryWarningObserver: NSObjectProtocol!

    /// Note, this is `private` to avoid subclassing this; singletons shouldn't be subclassed.
    ///
    /// Add observer to purge cache upon memory pressure.

    private override init() {
        super.init()

        memoryWarningObserver = NotificationCenter.default.addObserver(forName: .UIApplicationDidReceiveMemoryWarning, object: nil, queue: nil) { [weak self] notification in
            self?.removeAllObjects()
        }
    }

    /// The singleton will never be deallocated, but as a matter of defensive programming (in case this is
    /// later refactored to not be a singleton), let's remove the observer if deallocated.

    deinit {
        NotificationCenter.default.removeObserver(memoryWarningObserver)
    }

    /// Subscript operation to retrieve and update

    subscript(key: String) -> UIImage? {
        get {
            return object(forKey: key as AnyObject)
        }

        set (newValue) {
            if let object = newValue {
                setObject(object, forKey: key as AnyObject)
            } else {
                removeObject(forKey: key as AnyObject)
            }
        }
    }

}

您可以按照以下方式使用它:

ImageCache.shared["foo"] = image

let image = ImageCache.shared["foo"]

对于Swift 2.3示例,请参阅此答案的previous revision

答案 1 :(得分:3)

斯威夫特3:

class SomeClass
{
    static let sharedInstance = SomeClass() 

    fileprivate override init() {
        //This prevents others from using the default '()' initializer
        super.init()
    }

    func sayHello()
    { 
        print("Hello!")
    }   
}

调用一些方法:

SomeClass.sharedInstance.sayHello() //--> "Hello"

通过创建新的类实例(失败)来调用一些方法:

SomeClass().sayHello() //--> 'SomeClass' cannot be constructed it has no accessible initailizers

答案 2 :(得分:2)

以下是在swift 2.0中创建单例类的两种不同方法

方法1)这种方法是快速的目标C实现。

import UIKit

class SomeManager: NSObject {

       class var sharedInstance : SomeManager {

              struct managerStruct {

                   static var onceToken : dispatch_once_t = 0
                   static var sharedObject : SomeManager? = nil
              }

              dispatch_once(&managerStruct.onceToken) { () -> Void in
                   managerStruct.sharedObject = SomeManager()
              }
              return managerStruct.sharedObject!
       }

       func someMethod(){
              print("Some method call")
       }
 }

方法2)单行Singleton,不要忘记实现私有init(限制仅使用单例)

import UIKit

class SomeManager: NSObject {

       static let sharedInstance = SomeManager()

       private override init() {

       }

       func someMethod(){
            print("Some method call")
       }
  }

调用Singleton方法,如:

  SomeManager.sharedInstance.someMethod()

答案 3 :(得分:0)

Swift-5

要创建单例类:

import UIKit

final class SharedData: NSObject {
   static let sharedInstance = SharedData()

   private override init() { }

   func methodName() { }
}

要访问

let sharedClass = SharedClass.sharedInstance

OR

SharedClass.sharedInstance.methodName()