Singleton class for sharing data

对着背影说爱祢 提交于 2019-12-11 23:14:24

问题


I'm an android app developer and a beginner in swift. I'm trying to implement a singleton class whose data members are shared throughout the app (like Settings). Getting this done in android is pretty simple but I'm breaking my head to do it in swift.

Below is the code I've tried ..

public class DataSet
{
    public var notificationOnOff: Bool!
    public var interval: Int!
    public var alert: String!

    init()
    {
        self.notificationOnOff = true
        self.interval = 1;
        self.alert = nil;
    }

    init (onOff: Bool) {
        self.notificationOnOff = onOff
    }

    init (time: Int) {
        self.interval = time
    }

    init (stop: String) {
        self.alert = stop
    }
}

This class implementation couldn't persist the data. Is this the right way of doing it?

EDIT

For example, when I click switch in Settings view controller, I'm setting notificationOnOff like ..

dataset.notificationOnOff = DataSet(onOff: true) // value is set and able to print it

and using this value in another class like...

if dataset.notificationOnOff
{
 // do some stuff
}

So basically, the value is persisting only within the Setting class but not when I switch to other class.


回答1:


Solved!

I have used the below code to successfully implement this..

var instance: DataSet?
class Dataset {
...
    class var sharedInstance: DataSet {
        struct Static {
            static var instance: DataSet?
            static var token: dispatch_once_t = 0
        }

        dispatch_once(&Static.token) {
            Static.instance = DataSet()
        }

        return Static.instance!
    }
}

and in the other classes ..

dataset = Dataset.sharedInstance;


来源:https://stackoverflow.com/questions/27530993/singleton-class-for-sharing-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!