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