无法创建Singleton

时间:2016-07-03 13:01:31

标签: swift swift2 singleton

我想联系我,我联系了一下。

没有编译错误,但是当我运行init时,我没有进入“init”传递阶段。

可能是什么问题?

这是我的代码:

import UIKit

public class contact {

    var originalNumber: String = ""
    var e164Number: String = ""
    var contactImage: String = ""
    var name: String = ""

    init (originalNumber: String, name: String) {
        self.originalNumber = originalNumber
        self.name = name


    }


}

然后在我的contactDataClass中我做了:

import UIKit

import AddressBook // imports the framework

class contactsDataClass {

    var adbk : ABAddressBook!
    var localContacts = [contact]()

    init() {
        print("get to init")      
        contactsDataClass.sharedInstance.localContacts.append(contact(originalNumber: "0525222022", name: "try appent"))
        print("init pass")    

    } 

    struct Static {
        static var onceToken : dispatch_once_t = 0
        static var instance : contactsDataClass? = nil
    }

    class var sharedInstance : contactsDataClass {
        dispatch_once(&Static.onceToken){
            Static.instance = contactsDataClass()
        }
        return Static.instance!
    }      

}

1 个答案:

答案 0 :(得分:1)

您创建了无限递归

事实上这个块

class var sharedInstance : contactsDataClass {
    dispatch_once(&Static.onceToken){
        Static.instance = contactsDataClass()
    }
    return Static.instance!
}

调用此

init() {
    print("get to init")
    contactsDataClass.sharedInstance.localContacts.append(contact(originalNumber: "0525222022", name: "try appent"))
    print("init pass")    
} 

再次调用第一个块...

让我们清理您的代码

public class Contact {
    var originalNumber: String
    var e164Number = ""
    var contactImage = ""
    var name: String

    init (originalNumber: String, name: String) {
        self.originalNumber = originalNumber
        self.name = name
    }
}

class ContactManager {
    static let sharedInstance = ContactManager()
    private init() {}
    var adbk : ABAddressBook! // this is dangerous...
    var contacts = [Contact]()
}
  

正如您所看到的,在Swift中定义Singleton类比在Objective-C中更容易。

     

您只需隐藏默认initializer并创建static常量sharedInstance,如上所示。

用法

ContactManager.sharedInstance.contacts.append(Contact(originalNumber: "0525222022", name: "Test name"))

print(ContactManager.sharedInstance.contacts[0].name) // "Test name"