What is SharedInstance actually?

前端 未结 4 1804
礼貌的吻别
礼貌的吻别 2020-12-17 01:49

What is sharedInstance actually? I mean what is the usage?

Currently I\'m having some problem in communicating between 2 different files.

Here\'s my question:<

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-17 02:37

    Shared Instance is a process by which you can access the same instance or object of a class anywhere in the project. The main idea behind this is to return the same object each time a method is called so that the values/properties stored in the instance can be used anywhere in the application.

    This can be done in 2 simple process as follows:-

    1) Using a static variable initialised only once

    @implementation SharedInstanceClass
    
    static SharedInstanceClass *sharedInstance = nil;
    
    + (id)sharedInstanceMethod
    {
        @synchronized(self) {
            if (sharedInstance == nil) {
                sharedInstance = [SharedInstanceClass new];
            }
        }
        return sharedInstance;
    }
    
    @end
    

    2) Using GCD's :-

    + (id)sharedInstance{
        static dispatch_once_t onceToken;
        static SharedInstanceClass *sharedInstance = nil;
        dispatch_once(&onceToken, ^{
            sharedInstance = [SharedInstanceClass new];
        });
        return sharedInstance;
    }
    

    These have to be called as:-

    SharedInstanceClass *instance = [SharedInstanceClass sharedInstance];
    

    Thus everytime the same instance will be returned from the function and the values set to the properties will be retained and can be used anywhere in the application.

    Regards,

提交回复
热议问题