Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/113.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 初始化静态实例时如何运行代码?_Ios_Swift_Static_Static Methods_Swift5 - Fatal编程技术网

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