4

我有一个核心数据实体,其类型Person为可转换属性。ageAge

final class Person: NSManagedObject {
    @NSManaged public fileprivate(set) var age: Age
}

Age采用NSCoding协议,有两个变量valuescale,但只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一个实例PersonUITableViewCell。此实例 ( person) 的年龄值为 10.0,即person.age.value = 10.0,因此当以编程方式将比例更改为scale = 2.0通过 aUIStepper时,UITableViewCell显示20.0(即scale * value)。

但是,我发现如果我增加了足够多的次数,最终会在方法期间调用的类UIStepper的初始化,该方法返回给定的实例。这显然会导致类中的方法被调用,从而将属性的值重置为 1。AgePersontableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCellPersonIndexPathinit?(coder aDecoder: NSCoder)Agescale

请问为什么会发生这种情况,有没有办法解决这个问题?理想情况下,我希望该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]
}
4

1 回答 1

5

您的people属性是一个计算属性,这意味着您每次访问它时都会获得一个新的 people 数组people[indexPath.item]。因此,您每次调用时都在初始化一个新的 Person 实例func person(at:),我猜是在tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell.

通过更改步进值来测试这一点,然后使单元格从屏幕上消失并返回到同一个单元格。然后年龄将被重置。

只需让您的人员阵列像这样的存储属性。

private var people: [Person] = Array(database.people).sortedArray(using: Person.defaultSortDescriptors)
于 2018-08-16T06:48:38.503 回答