问题
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