Bry*_*yon 7 exception-handling ios swift
我对Swift中的异常处理有疑问.UIStoryboard类的UIKit文档指出,如果标识符为nil或故事板中不存在,则instantiateViewControllerWithIdentifier(identifier:String) - > 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;
}
Run Code Online (Sandbox Code Playgroud)
你应该怎么做/ try/catch来抛出像这样的异常的函数?
提前致谢.
布赖恩
这是在Swift中捕捉NSException中讨论的更普遍问题的特定情况。
总结似乎是迅速异常和objc异常是不同的。
在这种情况下,迅捷的文档说它抛出了一个Exception,但是无法捕获。至少听起来像是一个文档错误。
我不同意其他答案,因为缺少VC显然是程序员错误。如果行为如文献所述,则可以提出一种设计,在特定的情况下,根据VC是否存在,通用代码会做出不同的反应。必须添加其他配置以确保仅在存在VC时才尝试加载VC,这是对边缘案例漏洞等的邀请。cf更新异常。
| 归档时间: |
|
| 查看次数: |
2024 次 |
| 最近记录: |