iOS Swift:调用单例方法 3 次会导致应用程序崩溃 [英] iOS Swift: Calling a singleton method 3 times causes app to crash
问题描述
我有客观/快速的代码并排.我调用了 3 次 swift 单例方法.三遍之后就崩溃了.我有理由相信这可能是内存问题.这是我的代码
I have objective / swift code side by side. I am calling a swift singleton method 3 times. After three times it crashes. I have reason to believe this might be a memory problem. Here is my code
ViewController.m
ViewController.m
-(void)sharedData
{
// called three times
sharedData = [SharedData sharedData];
[sharedData initSyncManager];
}
Swift 共享数据类
Swift sharedData class
class func sharedData() -> SharedData
{
struct Singleton
{
static let instance = SharedData()
}
return Singleton.instance
}
func initSyncManager()
{
}
这一行的错误是 EXC_BAD_ACCESS (code=EXC_i386_GPFLT)
The error is EXC_BAD_ACCESS (code=EXC_i386_GPFLT) on this line
'return Singleton.instance'
我不知道为什么会发生这种情况.我在 initSyncManager
中根本没有代码,只有当我使用这段代码时才会发生这种崩溃
I have no idea why this is occurring. I have no code in initSyncManager
at all and this crash only happens when I use this piece of code
[sharedData initSyncManager];
如果我不调用该方法 3 次,则不会发生崩溃.
If I don't call the method 3 times, the crash doesn't occur.
推荐答案
你可以试试这个,因为我正在使用它(在 Swift 2.1 中)来创建单例类,它对我来说很好:
You may try this, as I am using this (in Swift 2.1) for creating singleton classes and it's working fine for me:
class var sharedInstance: SharedData {
struct Static {
static var onceToken: dispatch_once_t = 0
static var instance: SharedData? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = SharedData()
}
return Static.instance!
}
override init() {
super.init()
//initialisation
}
这篇关于iOS Swift:调用单例方法 3 次会导致应用程序崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!