//
//  File.swift
//  DateBook
//
//  Created by narita on 2017/09/06.
//  Copyright © 2017年 narita. All rights reserved.
//

import Cocoa
import ObjectiveC


// メソッドの入れ替え
extension NSObject
{
    // Method Swizzling
    // https://qiita.com/paming/items/25eaf89e4f448ab05752
    @objc class func exchangeInstanceMethod(from: Selector, to: Selector) -> Bool
    {
        let theFromMethod = class_getInstanceMethod(self, from)
        let theToMethod = class_getInstanceMethod(self, to)
        
        if theFromMethod != nil && theToMethod != nil
        {
            let didAddMethod = class_addMethod(self,
                                               from,
                                               method_getImplementation(theToMethod!),
                                               method_getTypeEncoding(theToMethod!))

            if didAddMethod
            {
                class_replaceMethod(self,
                                    to,
                                    method_getImplementation(theFromMethod!),
                                    method_getTypeEncoding(theFromMethod!))
            }
            else
            {
                method_exchangeImplementations(theFromMethod!, theToMethod!)
            }

            
            return true
        }
        
        return false
    }
    
}
