想从appdelegate调用ViewController的方法

我想在AppDelegate.m中调用ViewController的方法。 我在我的Viewcontroller有方法method()。我希望在appdelegate.m调用didSelectMethod()时调用它。 我已经打电话给这样的方法了。

 ViewController *vc=[[ViewController alloc]init]; [vc method]; 

方法被调用,但是与实际的方法具有相同的实例。 它具有所有的价值。 任何人都可以给我正确的代码,这是我想要的。

谢谢Jagveer Rana

虽然这已被正确回答的情况下,视图控制器是rootViewController ,为了完整起见,这里是如何得到这个与任何视图控制器的工作:

 // ViewController.h #import <UIKit/UIKit.h> @interface ViewController : UIViewController - (void)myMethod; @end // ViewController.m #import "ViewController.h" #import "AppDelegate.h" @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; appDelegate.myViewController = self; } - (void)myMethod { NSLog(@"Doing something interesting"); } // AppDelegate.h #import <UIKit/UIKit.h> #import "ViewController.h" @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @property (weak, nonatomic) ViewController *myViewController; @end // AppDelegate.m #import "AppDelegate.h" @implementation AppDelegate - (void)applicationDidEnterBackground:(UIApplication *)application { [self.myViewController myMethod]; } 

在应用程序中获取任何ViewController的同一个实例最简单的方法是一个接一个地跟踪它…就像从你的应用程序中的任何viewController

 [[[UIApplication sharedApplication] keyWindow] rootViewController]; 

或从appDelagate

 self.window.rootViewController; 

它会给你的rootViewController然后从这个rootViewController跟踪你想要的viewController。

在你的问题中,你创build了一个新的视图控制器实例,它不是视图层次结构的一部分,所以你不会通过调用方法(UI方式)看到任何效果。 (也没有通过xib / storyboard初始化,所以你的UI元素可能是零)

只要它是根视图控制器就可以通过窗口访问它(否则你将不得不在创build时find它或者保存对它的引用):

 ViewController *vc = (ViewController *)self.window.rootViewController; [vc method]; 

首先你需要在Appdelegate.h中声明你的ViewController类,然后在AppDelegate.h中创build你的UIViewController类的对象,像这样

 @class yourViewControllerClass; @property (nonatomic,strong) yourViewControllerClass *obj1; 

现在在AppDelegate.m中导入你的ViewController类,像这样

 #import yourViewControllerClass.h; 

现在在AppDeledate.m的方法applicationDidFinishLaunchingOption:创build你的viewController的一个新的对象,并将其分配给obj1,像这样

 yourViewControllerClass *obj2 = [[yourViewControllerClass alloc]init]; obj2 = self.obj1 

在这个代码的帮助下,你可以在视图控制器或对象之间parsing数据。现在在你的ViewController类的.m文件中,你必须导入Appdelegate.h,并将你的viewController对象的所有数据parsing为obj1,obj1将parsing这个数据到obj2与上面的代码helo)。[假设你的viewController类的对象为OBJ]。

 #import AppDelegate.h AppDelegate *ad = [[AppDelegate alloc]init]; ad.obj1 = OBJ 

注 – 我还没有testing这个代码..请保存您的项目首先在别的地方..根据我的知识回答..希望这会帮助你..谢谢

在.pch文件中写下这段代码

 #import "AppDelegate.h" #define DELEGATE ((AppDelegate*)[[UIApplication sharedApplication]delegate]) 

在任何ViewController中你想调用Delegate的方法,然后简单地写这个代码。

 [DELEGATE methodname];