簡體   English   中英

想從appdelegate調用ViewController的方法

[英]want to call ViewController's method from appdelegate

我想在AppDelegate.m中調用ViewController的方法。 我在Viewcontroller有method()方法。我希望在appdelegate.m調用didSelectMethod()時調用它。 我已經這樣叫方法了。

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

方法被調用,但與實際方法所擁有的實例不同。 它具有所有nill值。 任何人都可以為此給我正確的代碼。

謝謝Jagveer Rana

雖然對於視圖控制器為rootViewController的情況已正確回答了此rootViewController ,但出於完整性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];

}

在您的問題中,您將創建一個新的視圖控制器實例,該實例不屬於視圖層次結構,因此調用該方法(UI方式)不會產生任何效果。 (也沒有通過xib / storyboard進行初始化,因此您的UI元素可能為nil)

您可以通過窗口訪問它,只要它是根視圖控制器即可(否則在創建時必須找到它或保留對其的引用):

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

在您的應用中獲取anyViewController的相同實例的最簡單方法是對其進行逐一跟蹤...就像從您的應用中的任何viewController一樣

[[[UIApplication sharedApplication] keyWindow] rootViewController];

或從appDelagate

self.window.rootViewController;

它將為您提供rootViewController,然后從該rootViewController跟蹤所需的viewController。

首先,您在Appdelegate.h中聲明了ViewController類,並在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( (上面代碼的代碼)。[假定viewController類的對象為OBJ]。

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

注意-我尚未測試此代碼。.請先將您的項目保存在其他地方。.根據我的知識回答..希望這將對您有所幫助..謝謝

在.pch文件中編寫以下代碼

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

在任何ViewController中,您要調用Delegate的方法,然后只需編寫此代碼。

[DELEGATE methodname];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM