Skip to content

Instantly share code, notes, and snippets.

@towry
Created July 12, 2017 08:09
Show Gist options
  • Save towry/8102428caa63165fd8ca63fb315bd9e1 to your computer and use it in GitHub Desktop.
Save towry/8102428caa63165fd8ca63fb315bd9e1 to your computer and use it in GitHub Desktop.
associated objects demo in swift. objc_setAssociatedObject, objc_getAssociatedObject
// So associated objects just store object in anoter place, use property to
// associate the object with the class object.
import Foundation
let data: Data?
var dataKey: Void?
data = Data(count: 10)
data?.insert(9, at: 0)
class TestAssocicateObject {
init() {}
}
let a = TestAssocicateObject()
objc_setAssociatedObject(a, &dataKey, data, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
let b: Data? = objc_getAssociatedObject(a, &dataKey) as? Data
print(b![0])
@towry
Copy link
Author

towry commented Jul 12, 2017

Run it in terminal:

> swift associatedobject.swift

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment