想从 appdelegate 调用 ViewController 的方法 [英] want to call ViewController's method from appdelegate

查看:27
本文介绍了想从 appdelegate 调用 ViewController 的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to call ViewController's method in AppDelegate.m. i have method method() in my Viewcontroller .i want it to be called when didSelectMethod() called in appdelegate.m. I have called method like this.-

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

方法被调用但与实际方法具有不同的实例.它具有所有 nill 值.谁能给我正确的代码,我想要什么.

method is called but not having same instance as actually method having. it having all nill values. can anyone give me right code for this what i want.

谢谢贾格维尔拉纳

推荐答案

虽然在视图控制器是 rootViewController 的情况下已经正确回答了这个问题,但为了完整起见,这里是你如何得到这个使用任何视图控制器:

While this has been correctly answered for the case where the view controller is the rootViewController, for completeness sake here's how you can get this to work with any view controller:

// 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];

}

这篇关于想从 appdelegate 调用 ViewController 的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆