ObjectiveKit provides a Swift friendly API for a set of powerful Objective C runtime functions.
To use ObjectiveKit:
Import ObjectiveKit at the top of your Swift file:
import ObjectiveKitThe next step is to create an ObjectiveClass object typed for the class you want to modify or introspect:
letviewClass=ObjectiveClass<UIView>()If using ObjectiveKit on a custom Swift class, make sure that it inherits at some point from NSObject and that it is exposed to the Objective C runtime using the @objc flag.
You can learn more about classes at runtime with these handy introspection methods:
letmapViewClass=ObjectiveClass<MKMapView>()letivars= mapViewClass.ivars // An array of ivars.
letselectors= mapViewClass.selectors // An array of selectors.
letproperties= mapViewClass.properties // An array of properties.
letprotocols= mapViewClass.protocols // An array of protocols.Add a pre-existing selector from another class to your ObjectiveClass:
letviewClass=ObjectiveClass<UIView>()
viewClass.addSelector(#selector(testSelector), from:self.classForCoder)letview=UIView()
view.perform(#selector(testSelector))Add a custom method by providing the implementation with a closure:
letviewClass=ObjectiveClass<UIView>()
viewClass.addMethod(closureName, implementation:{print("hello world")})letview=UIView()
view.performMethod(closureName)ObjectiveKit also supports exchanging selectors in the same class:
letviewClass=ObjectiveClass<UIView>()
viewClass.exchangeSelector(#selector(UIView.layoutSubviews), with: #selector(UIView.xxx_layoutSubviews))Lastly, you can also create a custom ObjC class at runtime:
letruntimeClass=RuntimeClass(superclass:UIView.self)
runtimeClass.addIvar(ivarName, type:.Float)letruntimeObject= runtimeClass.allocate()
runtimeObject.setValue(4.0, forKey: ivarName)Setting up with CocoaPods
source'https://github.com/CocoaPods/Specs.git'pod'ObjectiveKit','~> 0.2'Carthage is a decentralized dependency manager that automates the process of adding frameworks to your Cocoa application.
You can install Carthage with Homebrew using the following command:
$ brew update
$ brew install carthageTo integrate ObjectiveKit into your Xcode project using Carthage, specify it in your Cartfile:
github "marmelroy/ObjectiveKit"
