1

I am trying to use singleton in my swift app.
I have a class which i used in ObjectiveC and now i am using it in swift using bridging-header...

In singleton class here is my code...

SharedManger.h file

 +(SharedManager *)sharedInstance;

 @property (strong, nonatomic) NSMutableDictionary *dictobject;

SharedManger.m file

 + (id)sharedInstance
 {
      static SharedManager *sharedMyManager = nil;
      @synchronized(self)
      {
         if (sharedMyManager == nil)
           {

              static dispatch_once_t onceToken;

               dispatch_once(&onceToken, ^{

                  sharedMyManager = [self loadInstance];

            });  
       }
  }

  return sharedMyManager;
}

+(instancetype)loadInstance
{
     NSData* decodedData = [NSData dataWithContentsOfFile: [SharedManager filePath]];

  if (decodedData)
   {
       SharedManager* sharedData = [NSKeyedUnarchiver unarchiveObjectWithData:decodedData];
       return sharedData;
   }

   return [[SharedManager alloc] init];
 }  

in viewcontroller.swift

 class var sharedInstance: viewcontroller {
    struct Static {
        static var onceToken: dispatch_once_t = 0
        static var instance: viewcontroller? = nil
    }
    dispatch_once(&Static.onceToken) {
        Static.instance = viewcontroller()
    }
    return Static.instance!
}

func sharedManager()->SharedManager{
    return SharedManager.sharedInstance()
}

Question:

  1. So this is right approach in swift or any better approach is there?

Edit:
storyboard hierarchy is navbar -> loginVC -> VC1 ->VC2 as @Schemetrical says...i used his approach as singleton....it works fine when i comes from loginVC i can access data from singleton....
but after one time login my root view controller changes and comes from VC1 and that time it display empty singleton....why is it so?

1 Answer 1

4

Swift 1.2 makes it really easy to create singletons. The static instance will be initialised only once and dictObject will be available for other classes to retrieve.

class SharedManager {

    static let sharedInstance = SharedManager()

    var dictObject = // some default value

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

6 Comments

ok...so i just need to make one .swift file instead of my 2 objectiveC files
Yes indeed. By default, within your project scope, all variables are available, but you can choose to make them private or public.
Could you rephrase that?
I wanted you to repeat the previous question because I didn't understand what you were trying to say ._.
as in question , i have viewcontroller.swift file ...so am i write right code in it or not?
|

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.