如何解决NSError init而不遇到无限循环

时间:2018-12-31 12:11:48

标签: ios swift nserror method-swizzling

晕眩时如何调用原始的NSError初始化方法?

我当前的实现方式

 extension NSError {

    @objc class func errorSwizzle() {
        guard let instance = class_getInstanceMethod(self, #selector(NSError.init(domain:code:userInfo:))),
            let swizzleInstance = class_getInstanceMethod(self, #selector(NSError.init(swizzleDomain:code:info:))) else { return }
        method_exchangeImplementations(instance, swizzleInstance)
    }

    @objc class func errorUnSwizzle() {
        guard let instance = class_getInstanceMethod(self, #selector(NSError.init(domain:code:userInfo:))),
            let swizzleInstance = class_getInstanceMethod(self, #selector(NSError.init(swizzleDomain:code:info:))) else { return }
        method_exchangeImplementations(swizzleInstance, instance)
    }

    @objc convenience init(swizzleDomain: String, code: Int, info: [String : Any]?) {

        /// infinite loop as it calls the swizzled init again.
        self.init(domain: swizzleDomain, code: code, userInfo: info)

        /// Do something.. 
    }
}

1 个答案:

答案 0 :(得分:2)

您已经交换了实现,这意味着您必须致电:

@objc convenience init(swizzleDomain: String, code: Int, info: [String : Any]?) {
    self.init(swizzleDomain: swizzleDomain, code: code, info: info)
}

因为self.init(swizzleDomain:...)将包含原始的初始化程序。