zoukankan      html  css  js  c++  java
  • Swift & the Objective-C Runtime

    关联对象(Associated Objects)

    extension UIViewController {
        private struct AssociatedKeys {
            static var DescriptiveName = "nsh_DescriptiveName"
        }
    
        var descriptiveName: String? {
            get {
                return objc_getAssociatedObject(self, &AssociatedKeys.DescriptiveName) as? String
            }
            set {
                if let newValue = newValue {
                    objc_setAssociatedObject(
                        self,
                        &AssociatedKeys.DescriptiveName,
                        newValue as NSString?,
                        UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC)
                    )
                }
            }
        }
    }

    方法交叉(Method Swizzling)

    extension UIViewController {
        public override class func initialize() {
            struct Static {
                static var token: dispatch_once_t = 0
            }
    
            // make sure this isn't a subclass        
            if self !== UIViewController.self {
                return
            }
    
            dispatch_once(&Static.token) {
                let originalSelector = Selector("viewWillAppear:")
                let swizzledSelector = Selector("nsh_viewWillAppear:")
    
                let originalMethod = class_getInstanceMethod(self, originalSelector)
                let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
    
                let didAddMethod = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))
    
                if didAddMethod {
                    class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
                } else {
                    method_exchangeImplementations(originalMethod, swizzledMethod);
                }
            }
        }
    
        // MARK: - Method Swizzling
    
        func nsh_viewWillAppear(animated: Bool) {
            self.nsh_viewWillAppear(animated)
            if let name = self.descriptiveName {
                println("viewWillAppear: (name)")
            } else {
                println("viewWillAppear: (self)")
            }
        }
    }
  • 相关阅读:
    各大型邮箱smtp服务器及端口收集
    阿里云邮箱POP3、SMTP设置教程
    thinkphp使用PHPMailer发送邮件
    SMTP错误码建议解决方法
    又来杭州了
    外企
    陈志武竞然是date的独立董事
    今天在当当上买了几本书,内有51反利的优惠券,也是一个suprise,
    工作 心态
    中国互联网创业,最好的城市是哪里?
  • 原文地址:https://www.cnblogs.com/newBlash/p/4884003.html
Copyright © 2011-2022 走看看