Swift:Singleton继承

时间:2014-11-26 08:59:58

标签: inheritance swift singleton

我在Swift中实现单例模式。我来到了一个点,我需要继承单例类。

我发现了一个提示:[[[self class] alloc] init]

如何在Swift中翻译它?

我想创造一些东西:

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

    return Static.instance
}

感谢。

5 个答案:

答案 0 :(得分:0)

这是我在swift中的单例继承的代码。它似乎在我的项目中工作......

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]()

答案 1 :(得分:0)

无需使用[[[self class] alloc] init]。你可以这样做:

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 :(得分:0)

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 :(得分:0)

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 :(得分:0)

Singleton意味着您不能拥有此类的多个实例。 所以构造函数应该是私有

class YourClassName {

  static let sharedInstance: YourClassName = YourClassName()

  private override init() {}
}