Jump to content

Add a variable to a class instance at runtime: Difference between revisions

Line 1,491:
 
<lang swift>import Foundation
 
let fooKey = UnsafeMutablePointer<Void>.alloc(1)
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
 
 
class MyClass { }
let e = MyClass()
 
// set
objc_setAssociatedObject(e, fooKey, 1, objc_AssociationPolicy(.OBJC_ASSOCIATION_RETAIN))
// get
if let associatedObject = objc_getAssociatedObject(e, fooKey) {
printlnprint("associated object: \(associatedObject)")
} else {
printlnprint("no associated object")
}</lang>
 
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.