/
NSObject+Extensions.swift
45 lines (37 loc) 路 1.22 KB
/
NSObject+Extensions.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//
// NSObject+Extensions.swift
// Withable
//
// Created by Geri Borb谩s on 08/04/2022.
// http://www.twitter.com/Geri_Borbas
//
import Foundation
extension NSObject {
struct Keys {
static var associatedObjects: UInt8 = 0
}
var associatedObjects: NSMutableDictionary {
get {
if let associatedObjects = objc_getAssociatedObject(self, &Keys.associatedObjects) as? NSMutableDictionary {
return associatedObjects
} else {
let associatedObjects: NSMutableDictionary = [:]
objc_setAssociatedObject(self, &Keys.associatedObjects, associatedObjects, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return associatedObjects
}
}
}
public func set(associatedObject: Any?, for key: AnyHashable) {
if let associatedObject = associatedObject {
associatedObjects[key] = associatedObject
} else {
remove(associatedObjectFor: key)
}
}
public func associatedObject(for key: AnyHashable) -> Any? {
associatedObjects[key]
}
func remove(associatedObjectFor key: AnyHashable) {
associatedObjects.removeObject(forKey: key)
}
}