iOS - 应用程序初始ViewController实例

问题描述:

有没有什么方法可以在不创建新实例的情况下访问它?正如我想要使用执行一个segue:iOS - 应用程序初始ViewController实例

[self performSegueWithIdentifier:@"loginSegue" sender:sender]; 

但是,如果我尝试创建一个实例,编译器说,segue不存在。我必须创建一个新实例的原因是因为我从另一个类中调用了ViewController类的一个方法。有没有办法从首先创建的实例运行该方法?

您是否在使用[UIStoryboard instantiateViewControllerWithIdentifier:]方法创建UIViewController实例?如果使用alloc-init实例化,它不会从storyboard实例化实例,所以它不会连接到segue。

这里是对UIStoryboard类的参考。

http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIStoryboard_Class/Reference/Reference.html

+0

我从来没有亲自创建它。我像你说的那样使用故事板。有没有办法访问它创建的实例? – 2012-01-05 02:46:29

+0

有,但不幸的是它不是很方便。您必须逐个遍历UIApplicateDelegate.window中的viewcontroller层次结构。例如[self.window.rootViewController.viewControllers objectAtIndex:0](如果您正在访问设置为ApplicationDelegate的self.window的根视图控制器的标签栏控制器中的第一项)。 – barley 2012-01-05 02:57:35

+0

啊,我错过了你说的标题中的初始viewcontroller。初始viewcontroller是窗口的rootviewcontroller,所以appDelegate.window.rootViewControlller会做。 – barley 2012-01-05 03:19:42

您可以将创建该对象的第一个实例保存到一个静态变量中,并定义一个静态方法来访问该对象。

static MyViewController *sharedInstance = nil; 

@implementation MyViewController 

- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle 
{ 
    ... init code here ... 

    if (!sharedInstance) { 
    sharedInstance = self; 
    } 

    return self; 
} 

- (id)initWithCoder:(NSCoder *)decoder 
{ 
    ... init code here ... 

    if (!sharedInstance) { 
    sharedInstance = self; 
    } 

    return self; 
} 

+ (MyViewController *)sharedInstance 
{ 
    if (!sharedInstance) 
    [[[self alloc] init] autorelease]; // will be retained inside the init method 

    return sharedInstance; 
} 

@end 

然后,在你的应用程序在其他地方,你可以使用访问该变量:

[MyViewController sharedInsatnce]; 

这不是一个很常用的模式,并有一些缺点(如:它永远不会被释放。所以确保它没有使用太多的内存),但UIKit/Foundation中的几个类使用它(NSFileManager,NSUserDefaults,NSBundle等)。