我有一个核心数据实体,其类型Person
为可转换属性。age
Age
final class Person: NSManagedObject {
@NSManaged public fileprivate(set) var age: Age
}
Age
采用NSCoding
协议,有两个变量value
和scale
,但只value
保存了 :
class Age: NSObject, NSCoding {
@objc public var value: Double
public var scale = 1.0
override public var description: String {
return "\(scale * value)"
}
func encode(with aCoder: NSCoder) {
aCoder.encode(value, forKey: #keyPath(value))
}
public convenience required init?(coder aDecoder: NSCoder) {
self.init(value: aDecoder.decodeDouble(forKey: #keyPath(value)))
}
init(value: Double) {
self.value = value
}
}
我在一个 中显示age
一个实例Person
的UITableViewCell
。此实例 ( person
) 的年龄值为 10.0,即person.age.value = 10.0
,因此当以编程方式将比例更改为scale = 2.0
通过 aUIStepper
时,UITableViewCell
显示20.0
(即scale * value
)。
但是,我发现如果我增加了足够多的次数,最终会在方法期间调用的类UIStepper
的初始化,该方法返回给定的实例。这显然会导致类中的方法被调用,从而将属性的值重置为 1。Age
Person
tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
Person
IndexPath
init?(coder aDecoder: NSCoder)
Age
scale
请问为什么会发生这种情况,有没有办法解决这个问题?理想情况下,我希望该scale
属性的值始终保持在UIStepper
.
感谢您对此事的任何帮助。
编辑
通过以下方式获得给定person
的 at an :indexPath
private var people: [Person] {
return Array(database.people).sortedArray(using: Person.defaultSortDescriptors)
}
private func person(at indexPath: IndexPath) -> Person {
return people[indexPath.item]
}