Ios 初始化静态实例时如何运行代码?
我正在使用这种模式:Ios 初始化静态实例时如何运行代码?,ios,swift,static,static-methods,swift5,Ios,Swift,Static,Static Methods,Swift5,我正在使用这种模式: open class CoreDataHub { public static let sharedInstance = CoreDataHub() open class func getThing() -> String { return "hello world" } init() { sharedInstance.getThing() } } 但我得到了以下错误: Static member 'getThi
open class CoreDataHub {
public static let sharedInstance = CoreDataHub()
open class func getThing() -> String {
return "hello world"
}
init() {
sharedInstance.getThing()
}
}
但我得到了以下错误:
Static member 'getThing' cannot be used on instance of type 'CoreDataHub'
我的目标是运行一些代码…即在初始化sharedInstance时调用getThing()。有什么想法吗?谢谢你你得到了
Static member 'getThing' cannot be used on instance of type 'CoreDataHub'
因为,使用sharedInstance
对象调用了getting()
静态方法
使用CoreDataHub.getting()
而不是sharedInstance.getting()
只要在
sharedInstance
的didSet
上调用getting()
,您能描述一下您试图使用的模式吗?我看不出你想达到什么目的。例如,为什么要忽略getting
的返回值?我不这么认为,这两个方案是相同的。我更新了这个答案,指出了他为什么会犯这个错误,以及如何克服这个错误。此外,通过使用public init.Yep,我的init也适用于CodeDataHub
的任何实例。我只是建议,他可以通过调用CoreDataHub.getting()
而不是sharedInstance.getting()
来修复这个错误。
public static let sharedInstance = CoreDataHub()
init() {
let value = CoreDataHub.getThing()
}