如何在实例化之前检查故事板中控制器的存在?

How to check existence of the controller in the storyboard before to instantiate it?

通过代码使用storoboard时,我们可以通过标识符实例化控制器,但是如果找不到具有该标识符的控制器将会崩溃。如何避免崩溃 and/or 提前检查控制器是否存在?

控制器实例化示例:

UIViewController *controller = [[UIStoryboard storyboardWithName:@"Settings" bundle:nil] instantiateViewControllerWithIdentifier:model.identifier];
[self.navigationController pushViewController:controller animated:YES];

试试这个。可能不是您要找的东西。这是一个变通办法。

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad 
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    _story = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
}

- (IBAction)go:(id)sender 
{
    SecondViewController *second;

    @try {
        second = [_story instantiateViewControllerWithIdentifier:@"Hello"];
    }
    @catch (NSException *exception) {
        NSLog(@"Reason %@" , exception.reason);
    }
    @finally {
        if (second == nil) {
            NSLog(@"VC %@" , second);
        }
    }


}
@end

对于这种情况,我有一个有用的扩展。 检查 GitHub: https://github.com/orkenstein/AAStoryboardInstantiate