Last active
September 17, 2015 10:17
-
-
Save webee/86992d8bac621a9756e7 to your computer and use it in GitHub Desktop.
associate object to class in swift.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // refer to: http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime#Swift | |
| // this is stupid, just inherit the target class. | |
| import Foundation | |
| class ObjectAssociateUtil { | |
| static var objKeys = [String:UnsafePointer<()>]() | |
| class func getAssociateObject<T:AnyObject, D>(target:T, by_key key:String) -> D? { | |
| let objKeyName = "\(NSStringFromClass(target.dynamicType)).\(key)" | |
| if let objKey = objKeys[objKeyName] { | |
| return objc_getAssociatedObject(target, objKey) as? D | |
| } | |
| return nil | |
| } | |
| class func getAssociateObject<T:AnyObject, D>(target:T, by_key key:String, with_default defValue:D!) -> D { | |
| let objKeyName = "\(NSStringFromClass(target.dynamicType)).\(key)" | |
| if let objKey = objKeys[objKeyName] { | |
| return objc_getAssociatedObject(target, objKey) as! D | |
| } | |
| return defValue | |
| } | |
| class func setAssociateObject<T:AnyObject, D>(target:T, by_key key:String, set_obj_as obj:D!) { | |
| let objKeyName = "\(NSStringFromClass(target.dynamicType)).\(key)" | |
| var fooKey: UnsafePointer<()> = nil | |
| withUnsafePointer(&fooKey) { ptr in | |
| fooKey = UnsafePointer<()>(ptr) | |
| } // one way to define a unique key is a pointer variable that points to itself | |
| objKeys[objKeyName] = fooKey | |
| objc_setAssociatedObject(target, fooKey, obj as! AnyObject, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN)) | |
| } | |
| } | |
| import UIKit | |
| extension UIView { | |
| var data:Int? { | |
| get { | |
| return ObjectAssociateUtil.getAssociateObject(self, by_key: "data") | |
| } | |
| set(newValue) { | |
| ObjectAssociateUtil.setAssociateObject(self, by_key: "data", set_obj_as: newValue) | |
| } | |
| } | |
| var name:String? { | |
| get { | |
| return ObjectAssociateUtil.getAssociateObject(self, by_key: "name") | |
| } | |
| set(newValue) { | |
| ObjectAssociateUtil.setAssociateObject(self, by_key: "name", set_obj_as: newValue) | |
| } | |
| } | |
| var count:Int { | |
| get { | |
| return ObjectAssociateUtil.getAssociateObject(self, by_key: "count", with_default: 0) | |
| } | |
| set(newValue) { | |
| ObjectAssociateUtil.setAssociateObject(self, by_key: "count", set_obj_as: newValue) | |
| } | |
| } | |
| } | |
| let v = UIView() | |
| v.data = 1 | |
| v.name = "webee" | |
| println(v.data!) | |
| println(v.name!) | |
| println(v.count) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment