5

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

In Objective-C

we can simple declare a property in .h like

@property (nonatomic,strong)UIImage *pic;

and define a sharedSingleton Method in .m

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

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

   }
   return sharedSingleton;
}
}

and call from any class with

 [SingletonClass sharedSingleton].pic

I am searching from last 2 hours but didn't find ant suitable tutorial to create this. please help me out to create a singleton class in swift and tell me how to call the instance variable.

M Swapnil
  • 2,361
  • 3
  • 18
  • 33
  • you mean to say something like globale variable which can be furthure used in other controllers ? – iRiziya Jul 16 '15 at 13:41

1 Answers1

12

its very simple in swift

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

and to access it

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

Here is very good guide about singleton

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

Bhavin Bhadani
  • 22,224
  • 10
  • 78
  • 108
  • thnxx a lot.. its so simple but no one posted this anywhere. thnxx once again. – M Swapnil Jul 16 '15 at 13:47
  • @EI Captain v2.0 Is there any difference if I use static var sharedInstance = SharedManager() instead of static let sharedInstance = SharedManager()? – kb920 May 19 '20 at 02:23