1

I'm trying to create int object variable in singleton class. This my ObjC version:

+(MyClass*) single
{
    static MyClass *shareObject = nil;
    static dispatch_once_t onceToken;
    dispatch_once ( &onceToken, ^{
        shareObject = [[self alloc] init];
        shareObject.myArray = [NSMutableArray new];
    });
    return shareObject;
}

Swift version:

class MyClass {

    static let sharedInstance = MyClass()
    var myArray = Array<Any>()
}

In case of the ObjC version I know myArray is init once. But my question to you guys in case of the Swift version. Does the myArray variable would be init once?

1
  • You may be interested to know that the accessor for a static (or global) stored variable actually currently uses dispatch_once under the hood on Apple platforms (compare stackoverflow.com/q/43374222/2976878) – making it more or less the direct equivalent of your Obj-C +single method. Commented May 19, 2017 at 18:39

1 Answer 1

1

You need to add a private initializer to make sure nobody else can manually instantiate MyClass.

class MyClass {
    static let sharedInstance = MyClass()

    var myArray = Array<Any>()

    private init() {}
}

This way there can only ever be one object of MyClass (the singleton), thus the initializers (= Array<Any>()) will only run once. And all this is thread safe.

Sign up to request clarification or add additional context in comments.

4 Comments

If I use the private init(). I'm getting initializer is inaccesible due to private protection. In the ObjC sample shareObject.myArray = [NSMutableArray new]; The array can be use on any class use by the singleton keeping the content
"I'm getting initializer is inaccesible due to private protection" That's the WHOLE point of a singleton. You want a single instance of an object, (sharedInstance as you named it), and no more.
You have to access the attributes of your singleton class using MyClass.sharedInstance.myArray.. You can't create an object of myclass .. You are trying to get its instance that's why it's giving an error
@UmerFarooq this is what I was looking for. I really appreciated

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.