Search code examples
objective-ciosuiviewcontrollerdelegatesrestkit

Getting the current instance of ViewController


I'm implementing a login system.

LoginViewController handles the View (duh!) for this system, LoginSession is a singleton that handles the authentication and storage of the current session, the authentication is made via RestKit.

//LoginViewController.m
- (IBAction)loginButtonPress:(id)sender {
    (...)
   [[LoginSession sharedInstance] authenticateUser:[username text] withPassword:[password text] andDomain:[domain text]];
}


//LoginSession.m
- (void) authenticateUser:(NSString *)userName withPassword:(NSString *)password andDomain:(NSString *)domain{
    (...)
     RKRequest * loginRequest = [[RKClient sharedClient] get:@"/login" queryParameters:loginData delegate:self];
    (...)
}

After this request is done, it calls the delegate:

//LoginSession.m
- (void)request:(RKRequest *)request didLoadResponse:(RKResponse *)response;

Which needs to call the LoginViewController back, to display an error or allow the user to access the application.

I tried instantiating the LoginViewController using the Storyboard, but turns out it were creating a new instance:

//LoginSession.m
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle: nil];
    
LoginViewController *loginViewController =
(LoginViewController *)[mainStoryboard instantiateViewControllerWithIdentifier: @"loginViewController"];

And I've even tried storing LoginViewController's self in a property on LoginSession: (which gets an error)

//LoginSession.m
@property (strong, retain) LoginViewController *loginViewController;

So, what's the proper way of contacting the current active instance of the ViewController?


Solution

  • You can use

    • Delegate Pattern, being used everywhere in iOS
    • Notification Pattern, e.g. NSNotificationCenter