Jared Chu Jared Chu - 1 month ago 10
Objective-C Question

Call the same view controller from many other view controller programmatically without using any segue

let storyboard = UIStoryboard(name: "MyStoryboardName", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("someViewController")


Run code above in multiple view controller they will init multiple
someViewController
. How to call the same
someViewController
instance in this case?

Answer

I think this is what you need to use for that effect Using a dispatch_once singleton model in Swift More specific: Swift :

 class SomeViewController {
      class var sharedInstance: SomeViewController {
        struct Static {
          static let instance: SomeViewController = UIStoryboard(name: "MyStoryboardName", bundle: nil).instantiateViewControllerWithIdentifier("someViewController")
        }
        return Static.instance
      }
    }

Objective C:

    + (instancetype)sharedInstance; // add this to SomeViewController.h file
    + (instancetype)sharedInstance { // and this in SomeViewController.m
       static SomeViewController *instance = nil;

       if (!instance) {
          UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MyStoryboardName" bundle:nil];
          instance = [storyboard instantiateViewControllerWithIdentifier:@"SomeViewController"];
       }

       return instance;
    }

then use with [SomeViewController sharedInstance]