Using NSObject’s +load and +initialize from Swift
Every once in awhile there comes a time when a class needs to do early autonomous initialisation that doesn’t belong into application launch handlers.
Error: method ‘load()’ defines Objective-C class method ‘load’, which is not permitted by Swift
Error: method ‘initialize()’ defines Objective-C class method ‘initialize’, which is not permitted by Swift
There’s a very simple solution to that — private Objective-C categories:
There are two gotchas:
- The class must inherit from
NSObjector any descendant. You can skip intermediate
swiftyInitializecallbacks and do the work straight in Objective-C. If
Foocannot inherit from
NSObjectyou can get away with an intermediate
FooObjCproxying class, which will invoke necessary callback within
Foo. The solution is pretty flexible, you get the idea!
- This works for free when class is compiled into main executable or framework, but static library will need
OTHER_LDFLAGSwhen linked. Static library might also require
OTHER_LDFLAGS, but I haven’t come across that.
As can see, this is a pretty neat solution without reinventing the wheel. Happy coding! ✌️
P. S. And if you ever need a high-quality and high-performance gif recorder checkout Gifox app, which I happen to work on. 🦊🙄