ios - 在 Swift 2 中动态检查对象类型

标签 ios swift swift2

我正在构建 iOS 应用程序的状态恢复。我目前有

func application(application: UIApplication, viewControllerWithRestorationIdentifierPath identifierComponents: [AnyObject], coder: NSCoder) -> UIViewController? {

    guard let controllerIdentifier = identifierComponents.last as? String else {
        return nil
    }

    guard let ctrl = self.window?.rootViewController else {
        return nil
    }

    if controllerIdentifier == "SetupPagesViewController" && ctrl is SetupPagesViewController {
        return ctrl
    } else if controllerIdentifier == "MainViewController" && ctrl is MainViewController {
        return ctrl
    }

    return nil
}

我发现最后一行有点难看。我可能会有更多 if 总是返回 Controller 。我正在尝试找到一个结构,在该结构中我不会拥有所有这些 if

我试过类似的东西:

    let checks = [
        "SetupPagesViewController": SetupPagesViewController.self,
        "MainViewController": MainViewController.self,
    ]

    if let clazz = checks[controllerIdentifier] where ctrl is clazz {
        return ctrl
    }

但是编译器不允许。我找不到一种方法来存储我的 class 类型以便在 if 中重用它。

这可能吗?如何?谢谢

最佳答案

您可以为此使用 Objective-C 运行时(由 Foundation 公开)的内省(introspection)工具,即 NSObjectisKindOfClass 方法:

let checks: [String:AnyClass] = [
    "SetupPagesViewController": SetupPagesViewController.self,
    "MainViewController": MainViewController.self,
]

if let clazz = checks[controllerIdentifier] where ctrl.isKindOfClass(clazz) {
    return ctrl
}

请注意,要使其正常工作,类必须继承自 NSObject

关于ios - 在 Swift 2 中动态检查对象类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32274511/

相关文章:

ios - 遍历来自 Alamofire 的 JSON 响应

ios - URLsession 委托(delegate)函数出错

ios - 尝试以编程方式实现约束时约束被忽略

ios - 以随机时间间隔定期将节点添加到场景中

ios - 使用 Swift 方法的 Crashlytics 报告难以阅读

Swift - 如何允许人们设置自己的 Firebase 后端?

ios - 如何访问 UICollectionViewController header 中的 UISegmentedControl?

ios - 自动布局顶部空间问题

ios - 应用程序从后台状态转到前台时的 OpenTok 视频通话问题

ios - 当我得到以下内容时,为什么必须输入?