Singleton class variable in swift?

I am trying to create a Singleton class where I want to create a UIImage instance.

In Objective-C

we can just declare the property in .h as

@property (nonatomic,strong)UIImage *pic;

      

and define sharedSingleton method in .m

+(SingletonClass*)sharedSingleton{
  @synchronized(self){

   if (!sharedSingleton) {
       sharedSingleton=[[SingletonClass alloc]init];

   }
   return sharedSingleton;
}
}

      

and call from any class using

 [SingletonClass sharedSingleton].pic

      

I've been looking for the last 2 hours but couldn't find ant a suitable tutorial to create this. please help me create a singleton class in swift and tell me how to call an instance variable.

+3


source to share


1 answer


its very easy in quick

class SharedManager {
   static let sharedInstance = SharedManager()
   var pic = UIImage()
}  

      

and access it



SharedManager.sharedInstance.pic = UIImage(named: "imagename")! 

      

Here is a very good tutorial about singleton

https://github.com/hpique/SwiftSingleton
https://thatthinginswift.com/singletons/

+7


source







All Articles