問題
requestAccessToAccountsWithType
など、UIApplication
に帰属するメソッドのコールバックを受けてViewを変えたいときは、AppDelegate
クラスの中でViewController
を取得せざるを得ない(と思う)。ので、そのメモ。
ゴール
AppDelegate
内で、定義済みのViewController
を取得し、そのメソッドを叩ける
解決
(プロジェクト名をFoo
としてます)
ViewControllerにIdentityを設定しないといけない
これを設定しとかないと名前で参照できない(適当にhoge
)
AppDelegateからViewControllerを取得
一例としてAppDelegate
クラスのdidFinishLaunchingWithOptions
を用いる。この中で以下のように書く
FooAppDelegate.m
#import "FooAppDelegate.h" // ↓これをimportしないとFooViewControllerに定義されたメソッド呼べない #import "FooViewController.h" @implementation FooAppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Mainストーリーボードを取得 UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; // ストーリーボードに定義されているViewControllerをidentityで取得 FooViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"hoge"]; // FooViewControllerに定義されているメソッド呼べるかテスト [viewController bar]; return YES; }
参考
- Zolea: storyboard上のViewControllerをAppDelegate上で扱う
- AppDelegate内でStoryboard のUIViewController を呼び出す方法 | 極上の人生
DRYな備忘録