12

I know there are duplicates of this question but my situation is different here.

When user goes back to the home (void)applicationDidEnterBackground gets invoked from the AppDelegate class. However once user presses home button, I don't want user to see this view controller again, so I have a method named (void)goToBeginning that switches to another view controller. I want to be able to call this method from AppDelegate. I don't really want to use NotificationCenter for this. Also the picked solution here: Calling view controller method from app delegate does not work for me as it initialises new object whereas I want to be able to call an object that is already in the view. How can I do that? I am using iOS 7 and XCode 5.

Community
  • 1
  • 1
Sarp Kaya
  • 3,686
  • 21
  • 64
  • 103
  • Great question +1, I marked as duplicate, because this is all similar concepts of a class calling another class, in your case you want to get the reference for the instantiated class (view controller), so that you can interact with UI elements, such as views... The question I consider to be the original is from 4 years ago and has many views and votes. – serge-k Feb 28 '16 at 00:22

1 Answers1

42
  1. Notification. But you don't want this.
  2. You can get the reference to your that viewController in the AppDelegate. Than call that (void)goToBeginning method in the (void)applicationDidEnterBackground

For example: In your ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    appDelegate.myViewController = self;
}

And in your AppDelegate:

@class MyViewController;

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (weak, nonatomic) MyViewController *myViewController;

@end

And in the AppDelegate's implementation:

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    [self.myViewController goToBeginning];
}
serge-k
  • 3,394
  • 2
  • 24
  • 55
sunkehappy
  • 8,970
  • 5
  • 44
  • 65
  • @Bryan Not me, the OP don't want this. "I don't really want to use `NotificationCenter`". You should read the question carefully. ^_^ – sunkehappy Feb 15 '15 at 02:46
  • Ah, sorry. Will delete my comment. – Bryan Feb 15 '15 at 17:38
  • Great answer +1. You will get a warning from compiler with just AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; Should change to AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; See http://stackoverflow.com/questions/5082738/ios-calling-app-delegate-method-from-viewcontroller – serge-k Feb 27 '16 at 22:34
  • Great answer... – Sipho Koza Feb 15 '17 at 09:44
  • 1
    nice workaround, though judging by the titles I do not get why is it marked as a duplicate - the other one's title is just the opposite – Boris Gafurov Feb 24 '17 at 21:01