如何在Appdelegate中的viewController中使用类实例?

时间:2014-07-19 20:57:44

标签: ios instance viewcontroller appdelegate

我在ViewController中有一个类实例和方法。 是否可以在appdelegate中访问此实例和方法?

就像:

@implementation FirstViewController
@synthesize myObject;

- (void)viewDidLoad
{
    [super viewDidLoad];
    myObject = [[myObject alloc] initWithFrame:........];
    [self.view addSubview:myObject];
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [myObject doSomething];
}

我希望在AppDelegate中调用相同的方法

- (void)applicationWillResignActive:(UIApplication *)application
{
    [myObject do Something];
}

有人有想法吗?

格尔茨

1 个答案:

答案 0 :(得分:0)

您可以像这样从rootViewConroller获取控制器并调用它的功能

- (void)applicationWillResignActive:(UIApplication *)application{ 

     UIViewController *controller = self.window.rootViewController;

     if([controller isKindOfClass:[UINavigationController class]]){
           FirstViewController *firstViewController;

            for (id vc in [((UINavigationController*)controller) viewControllers])
             {
                 if ([vc isKindOfClass:[FirstViewController class]])
                 {
                     [((FirstViewController *) vc) doSomething];
                     break;
                 }
             }
     }
     else if([controller isKindOfClass:[FirstViewController class]]){
             [((FirstViewController *) controller) doSomething];

     }else{
        //Not found
     }
}