gpt4 book ai didi

ios - 想从 appdelegate 调用 ViewController 的方法

转载 作者:行者123 更新时间:2023-12-01 17:30:29 25 4
gpt4 key购买 nike

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

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

方法被调用但没有与实际方法相同的实例。
它拥有所有 nill值(value)观。谁能给我我想要的正确代码。

谢谢
贾格维尔拉纳

最佳答案

虽然对于 View Controller 是 rootViewController 的情况已经正确回答了这个问题。 ,为了完整起见,这里是如何让它与任何 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];

}

关于ios - 想从 appdelegate 调用 ViewController 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26011117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com