美文网首页
Swift Runtime 练手之二 NSURL黑魔法

Swift Runtime 练手之二 NSURL黑魔法

作者: 布袋的世界 | 来源:发表于2017-03-17 17:12 被阅读63次

    感谢朋友MG明明 http://www.jianshu.com/u/57b58a39b70e 的指点,因为我是SWIFT直接入门,OC上写的runtime语法都不知如何移到SWIFT里应用,有个好友指点,确实可以少走很多弯路!

    此篇就直接上代码了,原理请看上一篇!

    NSURL黑魔法
    因为URL不能使用RunTime 因为URL是Struct结构体 ,而NSURL是Class类 集成NSObject ,所以要调用 NSURL来判断网址是否为空

     let urlString = "http://www.163.com/中文"
      override func viewDidLoad() {
            super.viewDidLoad()
     let url = NSURL(string: urlString)
     print (url!)
    }
    // URL为空
    // nil
    
    extension NSURL {
        
        open override static func initialize() {
            super.initialize()
     
            self.mySwizzle(cls: NSURL.self, origSEL: #selector(NSURL.init(string:)), newSEL: #selector(NSURL.newNSURL(withstr:)))
            
        }
        
        func newNSURL(withstr:String) -> NSURL?{
            
            let url = newNSURL(withstr:withstr)
            if url == nil {
                print ("URL为空")
            }
            return url
        }
        
        //交换方法函数
        class func mySwizzle(cls:AnyClass,origSEL:Selector,newSEL:Selector){
            //原有方法
            let originalMethod:Method = class_getInstanceMethod(cls, origSEL)
            //新方法(替换原有方法的新方法)
            let swizzleMethod:Method = class_getInstanceMethod(cls, newSEL)
            
            //先尝试給源SEL添加IMP,这里是为了避免源SEL没有实现IMP的情况
            let didAddMethod =  class_addMethod(cls, origSEL,
                                                method_getImplementation(swizzleMethod),
                                                method_getTypeEncoding(swizzleMethod))
            
            if didAddMethod {
                //添加成功:说明源SEL没有实现IMP,将源SEL的IMP替换到交换SEL的IMP
                class_replaceMethod(cls, newSEL,
                                    method_getImplementation(originalMethod),
                                    method_getTypeEncoding(originalMethod))
                
            }else {
                //添加失败:说明源SEL已经有IMP,直接将两个SEL的IMP交换即可
                method_exchangeImplementations(originalMethod, swizzleMethod)
            }
            
        }
    
        
    }
    

    相关文章

      网友评论

          本文标题:Swift Runtime 练手之二 NSURL黑魔法

          本文链接:https://www.haomeiwen.com/subject/cooenttx.html