Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active January 10, 2017 14:12
Show Gist options
  • Save KentarouKanno/03ade62ad31c34e4d29d13988f62f21b to your computer and use it in GitHub Desktop.
Save KentarouKanno/03ade62ad31c34e4d29d13988f62f21b to your computer and use it in GitHub Desktop.
Associated Objects

Associated Objects

★ 既存のクラスに新たにプロパティを追加する

class MyObject: NSObject {}

private var key = 0

extension MyObject {
    var str:String {
        get {
            return objc_getAssociatedObject(self, &key) as! String
        }
        set {
            objc_setAssociatedObject(self, &key, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC)
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment