ios - 快速检查对象的属性是否存在

标签 ios iphone xcode swift

我有下面的 UINib 扩展方法,我想知道我是否可以为未归档的 View 设置一个委托(delegate)

    public class func decodeView<T:UIView>(nibName name:String,className classType:T.Type,delegate:AnyObject) -> T {

    let nib = UINib(nibName: name)
    let topLevelObjects = nib.instantiateWithOwner(nil, options: nil)
    let view = topLevelObjects[0] as T
    view.setTranslatesAutoresizingMaskIntoConstraints(false)
    //check if view.delegate exists then view.delegate = delegate 
    return view
}

最佳答案

如果您询问 Swift 是否支持反射,TL;DR:您需要从 NSObject 继承。否则您获得的信息有限。

this question, Does Swift support reflection?你会得到关于你所拥有的可能性的更详细的讨论。

清除此部分后,可以在 SO Answer 中找到有关如何获取属性列表的示例。

尽管一种快速而肮脏的方法可能只是尝试访问该属性(使用 KVC)并在失败时捕获异常。 Swift 支持 Try/Catch/Finally 结构,但是这 nice hack允许您编写如下代码:

SwiftTryCatch.try({
         // try something
     }, catch: { (error) in
         println("\(error.description)")
     }, finally: {
         // close resources
})

关于ios - 快速检查对象的属性是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29469197/

相关文章:

c - iphone:如果 float 为负数,则转换为无符号整数的 float 将设置为 0?

iphone - uitableview reloadRowsAtIndexPaths 不工作

Swift for TensorFlow `error: Couldn' t 查找符号 : type metadata accessor for TensorFlow. Tensor`

iOS,带有调整类和 IBInspectables 的界面生成器错误?

ios - 如何根据设备动态计算 UITableViewCell 的高度

ios - 在 cellForRowAtIndexPath 循环中获取 UIView 类型的 subview

iphone - ECSliding,在LeftViewController下更改

ios - Xcode 4.3 : Codesign operation failed (Check that the identity you selected is valid)

php - 图像自动旋转

xcode - 显示 View 几秒钟(来自 NavController 的自定义推送)