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.

1
  • you mean to say something like globale variable which can be furthure used in other controllers ? Commented Jul 16, 2015 at 13:41

1 Answer 1

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/

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

2 Comments

thnxx a lot.. its so simple but no one posted this anywhere. thnxx once again.
@EI Captain v2.0 Is there any difference if I use static var sharedInstance = SharedManager() instead of static let sharedInstance = SharedManager()?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.