Swift: Singleton Inheritance

大憨熊 提交于 2019-12-12 04:55:00

问题


I'm implementing singleton pattern in Swift. I came to a point I need to inherit the singleton class.

I found a hint using this: [[[self class] alloc] init]

How to translate that in Swift?

I want to create something:

class var sharedInstance : MyClass //instanceType
{
    struct Static {                    // something like this
        static let instance: MyClass =  [[[self class] alloc] init]
    }

    return Static.instance
}

Thanks.


回答1:


No need to use [[[self class] alloc] init]. You can do like this:

MyClass.swift

import Foundation
import UIKit

let sharedInstance = MyClass()

class MyClass: NSObject {
     func sayHello(){
         println("Hello Nurdin!")
     }
}

ViewController.swift

/* Code everywhere.. */

sharedInstance.sayHello() //Hello Nurdin! appeared in console.

/* Code everywhere.. */



回答2:


for example ( use self.init() )

class A {
    var defaultPort: Int
    required init() {
        self.defaultPort = 404
    }
    class var shareInstance: A {
        struct Static {
            static var onceToken: dispatch_once_t = 0
            static var instance: A? = nil
        }
        dispatch_once(&Static.onceToken) {
            Static.instance = self.init()
        }
        return Static.instance!
    }
}



回答3:


class Base {

}

class A : Base {
    static let _a = Base.init()
    class var sharedInstance: Base {
        return _a
    }
}

let a = A.sharedInstance
let b = A.sharedInstance
a === b



回答4:


Singleton means that you cannot have more then one instance of this class. So constructor should be private.

class YourClassName {

  static let sharedInstance: YourClassName = YourClassName()

  private override init() {}
}



回答5:


Here is my code for singleton Inheritance in swift.It seems work in my project...

class BaseObject {
    required init(){
    }
    class func shareInstance() ->BaseObject{
        let classname = NSStringFromClass(self)
        if((dic[classname]) != nil) {
            return (dic[classname])!
        }
        else {
            var singletonObject = self()
            dic[classname] = singletonObject
            return singletonObject
        }
    }
}
var dic = [String: BaseObject]()


来源:https://stackoverflow.com/questions/27144915/swift-singleton-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!