ios - 如何覆盖 NSDate 描述? ..方法调配?

标签 ios swift swift2 nsdate method-swizzling

怎么调用

print(NSDate()) 

并没有收到通常的响应,而是获得了一个名为 getString() 的函数,它是 NSDateextension 的一部分.

Here's my extension:

extension NSDate {
    
   //NSDate to String
    public func getString() -> String {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
        dateFormatter.locale = NSLocale.currentLocale()
        
        return dateFormatter.stringFromDate(self)
    }
}

Please, note that I don't want to just use:

NSDate().getString()

I want to override original description of this class.

更新:

So, everything looks like the only option is Method Swizzling, if even possible.

Anyone interested in the bounty?

注意

I'm doing this just for personal growth and to get to understand the concept, not planning on shipping an App using it in this scenario, not even sure right now in what scenarios I could be using it.

最佳答案

import Foundation

extension NSDate: Streamable {
    public func writeTo<Target : OutputStreamType>(inout target: Target) {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
        dateFormatter.locale = NSLocale.currentLocale()

        print("without swizzling", dateFormatter.stringFromDate(self), toStream: &target)
    }
}

let date = NSDate()

print(date) // without swizzling 2016-03-05 00:09:34 +0100

打印“默认”/原始行为/使用

print(date.description)

如果您担心在您的扩展程序中使用打印,只需将其替换为

//print("without swizzling", dateFormatter.stringFromDate(self), toStream: &target)
let str = dateFormatter.stringFromDate(self)
str.writeTo(&target)

关于ios - 如何覆盖 NSDate 描述? ..方法调配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35159726/

相关文章:

ios - 适用于ReactiveCocoa 3.0的mapAs,filterAs,subscribeNextAs

ios - swift 在 ScrollView 内缩放 UIImageView

ios - 无法转换类型的值(CMAccelerometerData!,NSError!)

ios - AFNetworking 和处理 NSOperationQueue - 在完成时执行代码并跟踪进度

ios - [RN][IOS]是否可以将 React Native RCTLinking 与 RNFirebase 动态链接结合使用?

ios - 在类方法之外获取 Collection View 的 indexPath (JSQMessagesViewController)

ios - 适用于 iOS 的 Facebook SDK : FBSDKShareDialog is not shown

ios - 使用标识符执行 segue 不会在 swift 2 中工作

ios - swift 3 : Back gesture

ios - 为什么苹果的闭包声明缺少参数标签