![](/img/trans.png)
[英]Instantiating a View Controller programmatically with Storyboard from AppDelegate
[英]How to set properties on initial view controller (created in Storyboard) from AppDelegate?
我正在AppDelegate.m didFinishLauncingWithOptions
方法中調用API。 檢索到的JSON將轉換為對象的NSArray
。 我想將第一個視圖控制器的屬性設置為該數組,以便視圖控制器可以使用這些對象的latitude
和longitude
屬性來映射位置。
像這樣:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// array retrieved - in actual application, this is an API call and translation
Obj *object1 = [[Obj alloc] init];
Obj *object2 = [[Obj alloc] init];
Obj *object3 = [[Obj alloc] init];
NSArray *arrayOfObjectsToMap = [NSArray arrayWithObjects:object1, object2, object3, nil];
// pass object array along to first view controller
firstController.objectList = arrayOfObjectsToMap;
return YES;
}
我在弄清楚如何在Storyboard中創建的第一個控制器上設置屬性時遇到了麻煩。 AppDelegate的self.window.rootViewController
的類型為UIViewController
而我的初始控制器的類型為MapViewController
,其NSArray
屬性類似於上述示例中的objectList
屬性。
您可以使用以下方法使用segue將數據傳遞到視圖控制器。
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if([segue.identifier isEqualToString:@"showDetailSegue"]){
ViewControllerB *controller = (ViewControllerB *)segue.destinationViewController;
controller.isSomethingEnabled = YES;
}
}
請關注以下帖子以獲取更多詳細信息。 在視圖控制器之間傳遞數據
我決定通過將創建的對象保存到Core Data中來解決此問題(或者,我可以使用Singleton或其他存儲方式),並創建我的初始視圖控制器以從Core Data中讀取對象。
確保您導入了視圖控制器的頭文件:
#import "MapViewController.h"
然后,因為您知道您的初始視圖控制器是MapViewController類型,所以只需將強制類型轉換添加到表達式中:
((MapViewController *)firstController).objectList = arrayOfObjectsToMap;
為了使其更加安全,您可以檢查視圖控制器是否真的是MapViewController。
if ([firstController isKindOfClass:[MapViewController class]]) {
((MapViewController *)firstController).objectList = arrayOfObjectsToMap;
}
更新資料
另一個選擇是firstController
權,您可以在其中分配firstController
變量:
MapViewController *firstController = (MapViewController *)self.window.rootViewController;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.