Call a method from AppDelegate - Objective-C

前端 未结 3 1989
鱼传尺愫
鱼传尺愫 2021-02-19 13:10

I was trying to call an existing method of my ViewController.m from AppDelegate.m inside the applicationDidEnterBackground method,

3条回答
  •  清歌不尽
    2021-02-19 14:00

    You have two question here.

    1) What does the sharedApplication do?
    The [UIApplication sharedApplication] gives you UIApplication instance belongs to your application. This is centralised point of control for you App. For more information you can read UIApplication class reference on iOS developer site.

    2) Why must I set a delegate instead of just creating an instance of ViewController?
    Creating controller in AppDelegate again using alloc/init will create new instance and this new instance does not point to the controller you are referring to. So you will not get result you are looking for.
    However in this particular use case of applicationDidEnterBackground, you don't need to have reference of you controller in AppDelegate. You ViewController can register for UIApplicationDidEnterBackgroundNotification notification in viewDidLoad function and unregister in dealloc function.

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(yourMethod) name:UIApplicationDidEnterBackgroundNotification object:nil];
    
        //Your implementation
    }
    
    -(void)dealloc{
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
    

提交回复
热议问题