【发布时间】:2017-08-26 10:08:20
【问题描述】:
在我的应用程序中,我读取了 EKEvent 类型的日历事件,并使用大量计算变量进行了扩展,因此我可以轻松获取日历中每个事件的持续时间、工时数等。但在大规模情况下,性能很差 - 所以我想改用惰性变量来缓存我所有的额外数据。
因此,我想创建一个 EKEvent 的子类 - 称为 CustomEvent,它添加了惰性变量,但我的问题是 EKEventStore 总是返回 EKEvents,我需要将其转换为我的 CustomEvent 子类的实例,以便能够访问惰性变量等。
一个简单的类型转换是不够的,我在操场上尝试过,看看有什么可行的方法,但没有任何用处。我需要一个 CustomRectangle 的特殊构造函数,它可以从 NativeRectangle 初始化一个 CustomRectangle。另一种解决方案是创建一个将原始对象作为属性保存的包装类,但这不是我最喜欢的解决方案,因为我必须映射所有方法和属性
class NativeRectangle: NSObject {
var width: Int
var height: Int
init(width: Int, height: Int) {
self.width = width
self.height = height
super.init()
}
}
class CustomRectangle: NativeRectangle {
var area: Int { return width * height}
}
let rect = NativeRectangle(width: 100, height: 20)
let customRect = CustomRectangle(rect) // This fails, i need a constructor
print(customRect.area)
【问题讨论】:
标签: ios swift casting subclassing eventkit