Question

I am trying to set the delegate of a view controller from my app delegate. But it does not work.

AppDelegate.m:

UIStoryboard* sb = [UIStoryboard storyboardWithName:@"MainStoryboard"
                                              bundle:nil];

SFLoginViewController * LoginVC = (SFLoginViewController *)[sb
                                    instantiateViewControllerWithIdentifier:@"Login"];
LoginVC.delegate = self;

SFLoginViewController.m

- (IBAction)Login:(id)sender {

  NSLog(@"%@",self.delegate); //returns nil (!!)

  //It should call the delegate method here
  [[self delegate] LoginSucceeded];

}

any help?

Was it helpful?

Solution 2

Looking at the instantiateViewControllerWithIdentifier documentation...

Discussion You use this method to create view controller objects that you want to manipulate and present programmatically in your application. Before you can use this method to retrieve a view controller, you must explicitly tag it with an appropriate identifier string in Interface Builder.

This method creates a new instance of the specified view controller each time you call it.

I don't think the code you have in your appDelegate is returning the ViewController that is presented via the storyboard

OTHER TIPS

Why not set your delegate in the ViewController like this:

self.delegate = (YourAppDelegate *)[[UIApplication sharedApplication] delegate];

Then you'll be able to handle delegate events in your AppDelegate.

By doing this

(SFLoginViewController *)[sb instantiateViewControllerWithIdentifier:@"Login"];

you are creating a new instance of SFLoginViewController.

I assume that you already have an instance of this viewcontroller created from the storyboard. The instance from the storyboad is the one who call its method login:(id)sender and not the one you assigned the delegate.

Try @hw731 answer or you need to add the delegate to the instance created from the storyboard (not to the one you'are creating in your appdelegate).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top