Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Swift Method Swizzling 实现方式 #87

Open
resse92 opened this issue Sep 13, 2018 · 0 comments
Open

Swift Method Swizzling 实现方式 #87

resse92 opened this issue Sep 13, 2018 · 0 comments
Labels

Comments

@resse92
Copy link
Owner

resse92 commented Sep 13, 2018

public extension UIColor {
    @objc func colorDescription() -> String {
        return "print rainbow colours"
    }
    private static let swizzleDescriptionImplementation: Void = {
        let instance: UIColor = UIColor.red
        let aClass: AnyClass! = object_getClass(instance)
        let originalMethod = class_getInstanceMethod(aClass, #selector(description))
        let swizzleMethod = class_getInstanceMethod(aClass, #selector(colorDescription))
        if let originalMethod = originalMethod, let swizzleMethod = swizzleMethod {
            method_exchangeImplementations(originalMethod, swizzleMethod)
        }
    }()
    
    public static func swizzleDesription() {
        _ = self.swizzleDescriptionImplementation
    }
}

override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(tableView)
        
        print(UIColor.red)
        print(UIColor.green)
        UIColor.swizzleDesription()
        print("\nswizzled\n")
        print(UIColor.red)
        print(UIColor.red)
        UIColor.swizzleDesription()
        print("\nTrying to swizzle again\n")
        print(UIColor.red)
        print(UIColor.red)
    }

通过打印结果可见多次swizzleDescription操作,只会生效一次,并不会重复swizzle
详情请见Method swizzling in iOS swift

@resse92 resse92 added the iOS label Sep 13, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant