怎么调用
print(NSDate())
并没有收到通常的响应,而是获得了一个名为 getString()
的函数,它是 NSDate的
.extension
的一部分
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/