Skip to content

Instantly share code, notes, and snippets.

@SlaunchaMan
Created January 14, 2020 03:05
Show Gist options
  • Save SlaunchaMan/0e39185268bf5b482cdc590a44578e5e to your computer and use it in GitHub Desktop.
Save SlaunchaMan/0e39185268bf5b482cdc590a44578e5e to your computer and use it in GitHub Desktop.
Generate dynamic subclasses of Objective-C objects in Swift
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