无法在swift中使用objc_setAssociatedObject

时间:2017-06-16 11:08:48

标签: ios swift

我尝试将字符串与UIViewController相关联,并且代码无法关联" key"到UIViewController

private var key: Void?

objc_setAssociatedObject(self, &key, "key",.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
print(objc_getAssociatedObject(self, &key) as? String)

这里self是UIViewController而key是无效的?

这是我发现的一个演示,密钥没有定义,但代码工作

class MyClass {

    func printTitle(input: MyClass) {
        if let title = input.title {
            print("Title: \(title)")
        } else {
            print("nil")
        }
    }
}

// MyClassExtension.swift
private var key: Void?

extension MyClass {
    var title: String? {
        get {
            return objc_getAssociatedObject(self, &key) as? String
        }

        set {
            objc_setAssociatedObject(self,
                                     &key, newValue,
                                     .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
}

0 个答案:

没有答案