我在哪里在Swift中注册ValueTransformer? [英] Where do I register a ValueTransformer in Swift?

查看:118
本文介绍了我在哪里在Swift中注册ValueTransformer?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Swift中使用ValueTransformer(néNSValueTransformer),而我的应用程序打开的第一个窗口正在使用它.值转换器必须先通过ValueTransformer.registerValueTransformer(_:forName:)注册,然后才能通过用户界面运行时进行查询.

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.

NSValueTransformer的文档推荐+[AppDelegate initialize]中注册值转换器.但是,Swift不允许您覆盖+initialize.我尝试从applicationWillFinishLaunching(_)applicationDidFinishLaunching(_)注册,但是它们都发生得太晚了,并且我的窗口没有被填满,因为运行时找不到值转换器.

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?

推荐答案

是的,您可以在AppDelegate中注册值转换器.如果您想要更接近于ObjectiveC +initialize的东西,则可以使用类变量的延迟初始化.例如:

You are right, you can register your value transformers in the AppDelegate. If you want something that closer resembles ObjectiveC's +initialize you can use lazy initialization of a class variable. E.g:

class AppDelegate: NSObject, NSApplicationDelegate {

    static let doInitialize: Void = {
        // register transformers here
    }()

    override init() {
        super.init()
        AppDelegate.doInitialize
    }
}

如果要使转换器的内容更接近实际使用它们的类,则此模式也应适用于除AppDelegate以外的其他类.

This pattern should also work for classes other than the AppDelegate if you want to keep the transformers things closer to the classes that actually use them.

这篇关于我在哪里在Swift中注册ValueTransformer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆