Call a function in AppDelegate?

前端 未结 4 649
暖寄归人
暖寄归人 2020-12-19 13:14

Following the solution (the highest-voted answer actually) at UITextField Example in Cocos2d, I managed to do it except the line

[[[UIApplication sharedAppli         


        
相关标签:
4条回答
  • 2020-12-19 13:55
    1. Add your method in AppDelegate.h file such as:

      - (void)Welcome
      
    2. Implement the method in AppDelegate.m file such as:

       - (void)Welcome
       {
           NSLog(@"Welcome")
      
       }
      
    3. Set the UIApplication delegate in method such as:

      AppDelegate *appDelegate=[UIApplication sharedApplication] delegate];
      
      [appDelegate Welcome];
      
    0 讨论(0)
  • 2020-12-19 14:01

    Right now, your class doesn't know anything about your delegate's methods. You need to import your delegate into your implementation, not your interface (to avoid cycled imports).

    For example,

    #import "AppDelegate.h"
    

    Then you should cast the returned delegate in your nested method call to be your delegate type. For example:

    [(AppDelegate *)[[UIApplication sharedApplication] delegate] specifyStartLevel];
    
    0 讨论(0)
  • 2020-12-19 14:07

    -[UIApplication delegate] returns an object of type id<UIApplicationDelegate>, so the compiler only knows the methods that objects of that type respond to, even thought your custom delegate responds to specifyStartLevel. You can either ignore the warning, or cast the return value of -[UIApplication delegate]:

    [(YourCustomAppDelegate *) [[UIApplication sharedApplication] delegate] specifyStartLevel];
    
    0 讨论(0)
  • 2020-12-19 14:09

    You need to import the AppDelegate into the .m file where you use

    [[[UIApplication sharedApplication] delegate] specifyStartLevel];
    

    I like to import it with a header that gives me a shortcut.

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

    Then when I use it in any class I just

    #import "GlobalData.h"
    
    // to gain access to the delegate
    AppDelegate * appDelegate = APPDELEGATE;
    

    I use this approach because I can then store more #define's to some global constants (ie soundFXVolume - #define SOUND_FX_V 0.6)

    0 讨论(0)
提交回复
热议问题