获取ViewController的当前实例

时间:2012-09-06 05:33:37

标签: objective-c ios uiviewcontroller delegates restkit

我正在实施登录系统。

LoginViewController处理此系统的View(duh!),LoginSession是一个处理当前会话身份验证和存储的单例,通过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];
    (...)
}

完成此请求后,它会调用委托:

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

需要重新调用LoginViewController,显示错误或允许用户访问应用程序。

我尝试使用Storyboard实例化LoginViewController,但事实证明它正在创建一个新实例:

//LoginSession.m
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle: nil];

LoginViewController *loginViewController =
(LoginViewController *)[mainStoryboard instantiateViewControllerWithIdentifier: @"loginViewController"];

我甚至尝试将LoginViewController's self存储在LoginSession的属性中: (得到错误)

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

那么,联系ViewController的当前活动实例的正确方法是什么?

2 个答案:

答案 0 :(得分:0)

您可以使用

  • 委托模式,在iOS中随处可用
  • 通知模式,例如NSNotificationCenter

答案 1 :(得分:0)

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

@synthesize loginViewController;

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

推送或显示loginViewController

并使用loginViewController调用委托方法