ios – 使用swift进行异常处理

我对 Swift中的异常处理有疑问.
UIStoryboard类的UIKit文档声明了instantiateViewControllerWithIdentifier(identifier:String) – >如果标识符为nil或故事板中不存在,则UIViewController函数将抛出异常.但是,如果我像下面这样使用do / try / catch,我会收到一条警告“在’try’表达式中没有调用抛出函数.”

这只是一个警告,所以我认为这是一个智能问题;但是当我运行以下代码并故意使用无效标识符时,不会捕获异常并生成SIGABRT.

let storyboard = UIStoryboard.init(name: "Main",bundle: nil)
    do {
        let controller = try storyboard.instantiateViewControllerWithIdentifier("SearchPopup")

        // This code is only included for completeness...
        controller.modalPresentationStyle = .Popover
        if let secPopoverPresentationController = controller.popoverPresentationController {
            secPopoverPresentationController.sourceView = self.view
            secPopoverPresentationController.permittedArrowDirections = .Any
            secPopoverPresentationController.barButtonItem = self.bSearchButton
        }
        self.presentViewController(controller,animated: true,completion: nil)
        // End code included for completeness.
    }
    catch {
        NSLog( "Exception thrown instantiating view controller." );
        return;
    }

你应该怎么做/ try / catch来抛出像这样的异常的函数

提前致谢.

布赖恩

解决方法

instantiateViewControllerWithIdentifier不是投掷功能,你不能使用do … try … catch来处理它.如果故事板中没有视图控制器,则无法执行任何操作.这是程序员的错误,创建它的人应该处理这些问题.你不能因为这种错误而责怪iOS运行时.

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...