不能使用单例类来返回其属性

时间:2016-06-07 09:19:20

标签: swift

Hello Guys我有以下代码

class DeviceListViewController {
    private var currentPeripheral:BLEPeripheral?

    public class var sharedInstance: DeviceListViewController {
        struct Singleton {
            static let instance = DeviceListViewController()
        }
        return Singleton.instance
    }

    func getCurrentPeripheral() -> BLEPeripheral? {
        return currentPeripheral
    }

}

但是当我在另一个类中使用它时,如下面的

DeviceListViewController.getCurrentPeripheral() 

它给我一个错误告诉我以下内容 在类型“DeviceListViewController”上使用实例成员“getCurrentPeripheral”;你的意思是使用“DeviceListViewController”类型的值吗?

我不知道我在这里做错了什么。关于如何解决这个问题的任何建议?

P.S。 xcode的自动完成功能将ViewController作为参数与其一起传递

DeviceListViewController.getCurrentPeripheral(DeviceListViewController) 

但它导致相同的错误

2 个答案:

答案 0 :(得分:2)

您需要在共享实例上调用该方法,而不是在类

上调用
DeviceListViewController.sharedInstance.getCurrentPeripheral() 

答案 1 :(得分:0)

为避免使用MyClass.sharedInstance.method(),您可以使用此方法:

class DeviceListViewController {
    private var currentPeripheral:BLEPeripheral?

    public class var sharedInstance: DeviceListViewController {
        struct Singleton {
            static let instance = DeviceListViewController()
        }
        return Singleton.instance
    }

    class func getCurrentPeripheral() -> BLEPeripheral? {
        return DeviceListViewController.sharedInstance.currentPeripheral
    }

}

现在您可以使用MyClass.method()

相关问题