Created
July 12, 2017 08:09
-
-
Save towry/8102428caa63165fd8ca63fb315bd9e1 to your computer and use it in GitHub Desktop.
associated objects demo in swift. objc_setAssociatedObject, objc_getAssociatedObject
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
// 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]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Run it in terminal: