【问题标题】:AppDelegate to call function from m File + presentViewControllerAppDelegate 从 m File + presentViewController 调用函数
【发布时间】:2018-06-05 21:32:31
【问题描述】:

我有一个 AdIntegrator.mm 文件,其中包含创建表单的函数:

 -(void)createAndDisplayForm{
     AppDelegate* app = (AppDelegate*)[[UIApplication sharedApplication] delegate];          //add AppDelegate pointer
     _vc = app.window.rootViewController;

    //create form

    //presented using presentFromViewController:_vc
 }

我希望能够在需要时从我的AppDelegate.mm 再次使用此表单(如果User 希望再次看到此表单)。

我怎么称呼它?

我在AppDelegate.mm 中尝试了以下操作,但未显示任何视图:

AdIntegrator* opt = [[AdIntegrator alloc] init];
[opt createAndDisplayForm];

谁能告诉我在 AppDelegate 中使用此功能的最佳方式,以及确保可以再次看到 presentFromViewController。谢谢。

【问题讨论】:

    标签: objective-c appdelegate


    【解决方案1】:

    让我解释一下,AppDelegate 是一个Singleton 对象,因此您可以在 AppDelegate.h 中声明 AdIntegrator 类,例如这个:

    #import "AdIntegrator.h"
    
    @interface AppDelegate : UIResponder <UIApplicationDelegate>
    
    @property (strong, nonatomic) UIWindow *window;
    @property (nonatomic) AdIntegrator *adIntegratorObject;
    
    @end
    

    在您的 AppDelegate.m 中,您需要这样做:

    @interface AppDelegate ()
    @end
    
    @implementation AppDelegate
    
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        _AdIntegrator = [[AdIntegrator alloc] init];
        // or like this [AdIntegrator new];
    
        return YES;
    }
    

    _AdIntegrator 对象是 AppDelegate 单例中的引用 要从任何地方调用该方法,因此您可以从 OtherViewController.m 执行此操作,您需要在 OtherViewController.m 中 #import "AppDelegate.h" 来查看对象并调用方法:

    - (void)methodExampleFromOtherViewController
    {
        AppDelegate *appObject = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    
        // Calling your method in adIntegratorObject class
        [appObject.adIntegratorObject YOUR_METHOD_CALL];
    }
    

    您可以将 presentViewController:animated:completion: 方法与 AppDelegate 调用的 AdIntegrator 对象一起使用 :)

    【讨论】:

    • 感谢您的帮助。代码可以编译,但由于某种原因它没有调用该函数。我在开头放了一个NSLog,但并没有那么远。我还必须使用[AdIntegrator new];
    • 我将文件 AppDelegate.h 修改为 #import "AdIntegrator.h" 现在方法可见了,对不起我的伙伴,我希望它对你有帮助:)
    • 将来您可以创建自己的单例类并像这样在 AppDelegate.h 中声明单例并使用该对象中的其他类,因为您不想在 AppDelegate 中导入很多类.h :D
    猜你喜欢
    • 1970-01-01
    • 2012-11-05
    • 1970-01-01
    • 1970-01-01
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多