V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
lvlingsheng
V2EX  ›  Apple

如何在 Swift 3.1 中 override initialize()方法?

  •  
  •   lvlingsheng · Feb 28, 2017 · 7820 views
    This topic created in 3353 days ago, the information mentioned may be changed or developed.

    如果想在 Swift 中用 method swizzling ,原先的做法是需要重写 OC 中的 initialize 方法:

    open override static func initialize() { // Method Swizzling }

    但是在 Swift3.1 中,苹果不再建议在 swift 中 override initialize Method ,会提示: 'initialize()' defines Objective-C class method 'initialize', which is not guaranteed to be invoked by Swift and will be disallowed in future versions

    之前喵神在他的书的第二版里有提到 override initialize 方法来做 Method Swizzling , 但在第三版更新的时候删除了这部分内容,因为喵神觉得应该用更加 swift 化的方法来做。

    现在求问改怎么改或者怎么重写才能继续使用 Method Swizzling 呢?

    5 replies    2017-04-23 14:32:39 +08:00
    CommandZi
        1
    CommandZi  
       Feb 28, 2017
    没人答,我来班门弄斧一下。
    先贴 Gist 地址: https://gist.github.com/chn-lyzhi/6056f3ef48d997629b438254c67d781c
    代码应该很清楚了,我这里是 Swift 3 下使用 Objective-C Runtime 里的 Method Swizzling 方法来做页面统计。你可以根据自己的需求改写。
    lvlingsheng
        2
    lvlingsheng  
    OP
       Feb 28, 2017
    @CommandZi 哈,你的代码没有问题,但是如果在 Xcode8.3 中, IDE 会对你里面的 open override static func initialize()警告,我的问题就是有没有其他办法可以解决这个问题。
    CommandZi
        3
    CommandZi  
       Mar 1, 2017
    @lvlingsheng 其他的比如协议加协议扩展也是可以的,但是没有办法像 Method Swizzling 这样对代码无感知地更少侵入性地作修改操作。
    关于那个警告,你可以像这里最后说的那样来消除警告: http://nshipster.cn/swift-objc-runtime/
    > 在 app delegate 中实现方法交叉
    hstdt
        4
    hstdt  
       Mar 1, 2017 via iPhone
    我觉得既然苹果都说了 swizzle 只能用于 oc ,那就把这部分东西写在 oc 文件里面,然后 bridge 引用,避免以后 swift 语法变化。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2473 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 15:40 · PVG 23:40 · LAX 08:40 · JFK 11:40
    ♥ Do have faith in what you're doing.