I'm trying to use a ValueTransformer
(né NSValueTransformer
) in Swift that is being used by the first window that my application opens. Value transformers need to be registered with ValueTransformer.registerValueTransformer(_:forName:)
before they can be queried by the user interface runtime.
The documentation for NSValueTransformer
recommends registering value transformers in +[AppDelegate initialize]
. However, Swift doesn't allow you to override +initialize
. I tried to register from applicationWillFinishLaunching(_)
and applicationDidFinishLaunching(_)
, but they both happen too late and my window doesn't get filled because the runtime can't find the value transformer.
Where should I register my value transformer?
In AppDelegate you can use a dummy property of type Void
with a closure. The closure is even executed before init
private let transformer : Void = {
let myTransformer = MyValueTransformer()
ValueTransformer.setValueTransformer(myTransformer, forName:NSValueTransformerName("MyValueTransformer"))
}()
I found that I can count on the app delegate class to be init
ialized early and only once, so I stuck my ValueTransformer.registerValueTransformer
call in it.
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
override init() {
ValueTransformer.setValueTransformer(MyValueTransformer(), forName: NSValueTransformerName("MyValueTransformer"))
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With