美文网首页
Associated Object

Associated Object

作者: fordring2008 | 来源:发表于2017-02-05 12:26 被阅读9次

    // Associated Object// 动态添加成员变量。 直接添加成员变量是不允许的,利用 OC 的运行时和 KVC 特性,我们可以在运行时想一个对象添加值存储。// 利用 property 配合 Associated Object // 添加 和 获得的方法/*func objc_getAssociatedObject(object: AnyObject!,                              key: UnsafePointer) -> AnyObject!func objc_setAssociatedObject(object: AnyObject!,                              key: UnsafePointer,

    value: AnyObject!,

    policy: objc_AssociationPolicy)

    */

    class MyClass{ }

    private var titleKey: Void?

    extension MyClass {

    var title : String? {

    get{

    return objc_getAssociatedObject(self, &titleKey) as? String

    }

    set{

    objc_setAssociatedObject(self, &titleKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)

    }

    }

    }

    // 测试

    func printTitle(_ input: MyClass){

    if let title = input.title {

    print("Title: \(title)")

    } else {

    print("没有设置")

    }

    }

    let a = MyClass()

    print(a)

    a.title = "Swifter.tips"

    print(a.title) // Optional("Swifter.tips")

    相关文章

      网友评论

          本文标题:Associated Object

          本文链接:https://www.haomeiwen.com/subject/agyjittx.html