-->

想打电话从AppDelegate中视图控制器的方法(want to call ViewControl

2019-10-21 01:10发布

我想打电话ViewController的在AppDelegate.m方法。 我有方法()方法在我Viewcontroller 。我想它的时候didSelectMethod()调用,以被称为appdelegate.m 。 我所说的方法类似this.-

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

方法被调用,但没有相同的实例作为实际的方法有。 它拥有所有nill值。 谁能给我这个正确的代码我想要什么。

谢谢Jagveer拉纳

Answer 1:

虽然这已经回答正确的,其视图控制器是时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];

}


Answer 2:

获得anyViewController的同一实例在您的应用程序最简单的方法是跟踪一个一个...喜欢任何的viewController在您的应用程序

[[[UIApplication sharedApplication] keyWindow] rootViewController];

或者从appDelagate

self.window.rootViewController;

它会给你的RootViewController的然后从该RootViewController的跟踪所需的viewController。



Answer 3:

在你的问题,你创建一个新的视图控制器实例,它是不是视图层次的一部分,所以你不会看到通过调用方法(UI明智)任何影响。 (此外,它不是通过厦门国际银行/故事板初始化,您的UI元素可能会是零)

可以,只要它是根视图控制器(否则你必须找到它或创建时保持对它的引用)通过窗口访问:

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


Answer 4:

首先,你必须声明你的ViewController类的Appdelegate.h,并在AppDelegate.h你的UIViewController类的一个对象,像这样

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

现在导入您的ViewController类AppDelegate.m,这样

#import yourViewControllerClass.h;

现在,在AppDeledate.m的方法applicationDidFinishLaunchingOption:创建您的viewController的一个新对象,并将其分配给OBJ1,这样

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

有了这个代码的帮助,你可以分析你的ViewController类的.m文件,你必须导入Appdelegate.h并从您的viewController对象分析所有数据OBJ1和OBJ1将解析数据OBJ2 viewcontrollers或objects..Now之间的数据(与上面的代码的直升机)。假设你的viewController类作为OBJ的对象。

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

注意 - 我没有测试过这code..please保存根据我knowledge..hope这将帮助你you..Thank项目第一某处else..answered



Answer 5:

在.PCH文件中编写代码

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

在任何的ViewController你想调用委托的方法则简单地编写代码。

[DELEGATE methodname];


文章来源: want to call ViewController's method from appdelegate