I was trying to call an existing method of my ViewController.m
from AppDelegate.m
inside the applicationDidEnterBackground
method,
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];
}