Created
January 14, 2020 03:05
-
-
Save SlaunchaMan/0e39185268bf5b482cdc590a44578e5e to your computer and use it in GitHub Desktop.
Generate dynamic subclasses of Objective-C objects in Swift
This file contains 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
import Foundation | |
import ObjectiveC | |
private var subclassCounts: [String: Int] = [:] | |
func GenerateDynamicSubclass<T: NSObject>(of class: T.Type) -> T.Type! { | |
let oldClassName = NSStringFromClass(`class`) as String | |
var subclassCount = subclassCounts[oldClassName] ?? 0 | |
let className = "\(oldClassName)_DynamicSubclass_\(subclassCount)" | |
subclassCounts[oldClassName] = subclassCount + 1 | |
guard let newClass = objc_allocateClassPair(T.self, (className as NSString).utf8String!, 0) else { return nil } | |
objc_registerClassPair(newClass) | |
return newClass as! T.Type | |
} | |
GenerateDynamicSubclass(of: NSObject.self).init().debugDescription | |
// <NSObject_DynamicSubclass_0: 0x101066c30> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment