代码之家  ›  专栏  ›  技术社区  ›  Nitish

快速旋转法

  •  7
  • Nitish  · 技术社区  · 6 年前

    这是用Objective-C编写的快速代码的方法。我很难用Swift转换这个。

    void MPApplicationDidRegisterForRemoteNotificationsWithDeviceToken(id self, SEL _cmd, UIApplication *application, NSData *deviceToken) {
        [[MPPush shared] appRegisteredForRemoteNotificationsWithDeviceToken:deviceToken];
    
        IMP original = [MPAppDelegateProxy originalImplementation:_cmd class:[self class]];
        if (original)
            ((void(*)(id, SEL, UIApplication *, NSData*))original)(self, _cmd, application, deviceToken);
    }  
    

    var MPApplicationDidRegisterForRemoteNotificationsWithDeviceToken: Void {
            //     TODO:   MPPush.shared.app
    
            let original = MPAppDelegateProxy.proxyAppDelegate.originalImplementation(selector: cmd, forClass: type(of: self))
        }(self: Any, _cmd: Selector, application: UIApplication, deviceToken: Data)
    
    1 回复  |  直到 5 年前
        1
  •  5
  •   ielyamani    5 年前

    扩展课程:

    extension YourClassName {
        static let classInit: () -> () = {
            let originalSelector = #selector(originalFunction)
            let swizzledSelector = #selector(swizzledFunction)
            swizzle(YourClassName.self, originalSelector, swizzledSelector)
        }
    
        @objc func swizzledFunction() {
            //Your new implementation
        }
    }
    

    YourClassName )应该继承自 NSObject originalSelector 应该是一个 dynamic

    swizzle

    private let swizzle: (AnyClass, Selector, Selector) -> () = { fromClass, originalSelector, swizzledSelector in
        guard 
            let originalMethod = class_getInstanceMethod(fromClass, originalSelector),
            let swizzledMethod = class_getInstanceMethod(fromClass, swizzledSelector)
            else { return }
        method_exchangeImplementations(originalMethod, swizzledMethod)
    }
    

    旋转 在你要做旋转动作的课堂上。例如 AppDelegate AppDelegate.init() :

    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {
        override init() {
            super.init()
            YourClassName.classInit()
        }
    }
    

    例子

    exchanges the implementation 接受一个参数的两种方法之一:

    class Example: NSObject {
        @objc dynamic func sayHi(to name: String) {
            print("Hi", name)
        }
    }
    
    extension Example {
        public class func swizzleMethod() {
            guard
                let originalMethod = class_getInstanceMethod(Example.self, #selector(Example.sayHi(to:))),
                let swizzledMethod = class_getInstanceMethod(Example.self, #selector(Example.sayHello(to:)))
                else { return }
            method_exchangeImplementations(originalMethod, swizzledMethod)
        }
        @objc func sayHello(to name: String) {
            print("Hello", name)
        }
    }
    
    Example.swizzleMethod()
    
    let a = Example()
    a.sayHi(to: "Nitish")        //Hello Nitish