added iOS source code
[wl-app.git] / iOS / Pods / MenuItemKit / MenuItemKit / Internals.swift
1 //
2 //  Internals.swift
3 //  MenuItemKit
4 //
5 //  Created by CHEN Xian’an on 1/17/16.
6 //  Copyright © 2016 lazyapps. All rights reserved.
7 //
8
9 import ObjectiveC.runtime
10
11 let imageItemIdetifier = "\u{FEFF}\u{200B}"
12
13 let blockIdentifierPrefix = "_menuitemkit_block_"
14
15 func setNewIMPWithBlock<T>(_ block: T, forSelector selector: Selector, toClass klass: AnyClass) {
16   let method = class_getInstanceMethod(klass, selector)
17   let imp = imp_implementationWithBlock(unsafeBitCast(block, to: AnyObject.self))
18   if !class_addMethod(klass, selector, imp, method_getTypeEncoding(method!)) {
19     method_setImplementation(method!, imp)
20   }
21 }
22
23 @nonobjc extension NSObject {
24
25   var imageBox: Box<UIImage?> {
26     let key: StaticString = #function
27     return associatedBoxForKey(key, initialValue: nil)
28   }
29
30   var actionBox: Box<MenuItemAction?> {
31     let key: StaticString = #function
32     return associatedBoxForKey(key, initialValue: nil)
33   }
34
35   func associatedBoxForKey<T>(_ key: StaticString, initialValue: @autoclosure () -> T) -> Box<T> {
36     guard let box = objc_getAssociatedObject(self, key.utf8Start) as? Box<T> else {
37       let box = Box(initialValue())
38       objc_setAssociatedObject(self, key.utf8Start, box as AnyObject, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
39       return box
40     }
41
42     return box
43   }
44
45 }
46
47 // MARK: Box wrapper
48 final class Box<T> {
49
50   var value: T
51
52   init(_ val: T) {
53     value = val
54   }
55   
56 }