不使用任何segue,以编程方式从多个其他视图控制器调用相同的视图控制器

时间:2016-10-11 07:51:56

标签: ios objective-c

someViewController

在多个视图控制器中运行上面的代码,它们将初始化多个someViewController。在这种情况下如何调用相同的{{1}}实例?

2 个答案:

答案 0 :(得分:0)

我认为这是您需要使用的效果Using a dispatch_once singleton model in Swift 更加具体: 斯威夫特:

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

目标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;
    }

然后使用[SomeViewController sharedInstance]

答案 1 :(得分:0)

目标C

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
someViewController *afv=[storyboard instantiateViewControllerWithIdentifier:@"someViewController"];
afv.getdata();
[self.sideMenuViewController setContentViewController:afv animated:YES];

<强>夫特

let mainStoryboard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let someobject: someViewController = (mainStoryboard.instantiateViewControllerWithIdentifier("someViewController") as! someViewController)
someobject.getdata()
self.navigationController?.pushViewController(someobject, animated: true)