ios - 想从 appdelegate 调用 ViewController 的方法

标签 ios objective-c methods uiviewcontroller appdelegate

我想调用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/

相关文章:

javascript - iOS Phonegap 多行文本选择错误?

ios - 在嵌套 block 中调用 dispatch_group_notify 的次数与调用 dispatch_group_leave 的次数一样多

objective-c - 如何获取 Mac 桌面大小

Java 重写 throws 子句

java - 无法从 View MainActivity.java 类型对非静态方法 invalidate() 进行静态引用

iphone - JSON 响应显示在警报 View 中?

ios - 来自远程 I/O 单元的原始音频数据的测量单位是什么?

ios - 将新的获取请求模板添加到 Core Data 会破坏以前版本的模型吗?

objective-c - 为什么在 for-in 循环中可以将一种类型的指针赋值给另一种类型的指针?

java - 如何正确调用方法