Is it possible in Swift to add variables to an object at runtime? -
specifically, add variable of type enum instance of uiview, without subclassing or create extension.
thanks.
the previous answer objc_setassociatedobject() right approach, think apple's apis have not yet been vetted, because i've had difficulty using them way think ought used. (i shouldn't have muck unsafe pointers , such.) here's solution i'm using now.
first, need bit of objective-c glue (follow apple's instructions mixing objective-c , swift in same project:
// runtimeglue.h // should included bridging header. @import foundation; void setassociatedobject_glue(nsobject *object, const nsstring *key, nsobject *value); nsobject *getassociatedobject_glue(nsobject *object, const nsstring* key); // runtimeglue.m #import "runtimeglue.h" #import <objc/runtime.h> void setassociatedobject_glue(nsobject *object, const nsstring *key, nsobject *value) { objc_setassociatedobject(object, (__bridge const void *)(key), value, objc_association_retain_nonatomic); } nsobject *getassociatedobject_glue(nsobject *object, const nsstring* key) { return objc_getassociatedobject(object, (__bridge const void *)(key)); } next, swift methods you'll call rest of program:
// runtime.swift import foundation public func setassociatedobject(#object: nsobject, #key: nsstring, #value: nsobject?) { setassociatedobject_glue(object, key, value) } public func getassociatedobject(#object: nsobject, #key: nsstring) -> nsobject? { return getassociatedobject_glue(object, key) } finally, example of use tag particular view controller's view "debugging".
// myviewcontroller.swift import uikit let debugkey: nsstring = "debugkey" class myviewcontroller: uiviewcontroller { override func viewdidload() { super.viewdidload() setassociatedobject(object: self.view, key: debugkey, value: "debugging") } override func viewwillappear(animated: bool) { super.viewwillappear(animated) let val = getassociatedobject(object: self.view, key: debugkey) println("val:\(val)") } } this approach lets pass nil value setter in order clear value key, , returns optional getter. note key argument must identical in both cases (k1 === k2) , not merely equivalent (k1 == k2).
also note lets tag instances of nsobject or subclasses-- not work swift native classes. value must nsobject subclass, both strings , number literals automatically bridge objective-c, don't need explicit casting.
Comments
Post a Comment