繁体   English   中英

UITableView“cellForRowAt:indexPath”偶尔在核心数据属性上调用“init?(coder aDecoder:NSCoder)”

[英]UITableView “cellForRowAt: indexPath” Occasionally Calling “init?(coder aDecoder: NSCoder)” on Core Data Attribute

我有一个核心数据实体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
    }

}

我在UITableViewCell显示Person实例的age 此实例( person )的年龄值为10.0,即person.age.value = 10.0 ,这样当通过UIStepper以编程方式更改scale = 2.0以表示scale = 2.0UITableViewCell显示20.0 (即scale * value )。

但是 ,我发现如果我增加UIStepper足够的次数,最终会在tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell方法中调用PersonAge类的初始化,该方法返回一个实例Person在给定的IndexPath 这显然会导致调用Age类中的init?(coder aDecoder: NSCoder)方法,这会将scale属性的值重置为1。

请问为什么会发生这种情况,是否有办法解决这个问题? 理想情况下,我希望scale属性的值始终保持在UIStepper上设置的UIStepper

感谢您对此事的任何帮助。

编辑

indexPath给定person通过以下方式获得:

private var people: [Person] {
    return Array(database.people).sortedArray(using: Person.defaultSortDescriptors)
}

private func person(at indexPath: IndexPath) -> Person {
    return people[indexPath.item]
}

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

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

只需让你的人员数组成为这样的存储属性。

private var people: [Person] = Array(database.people).sortedArray(using: Person.defaultSortDescriptors)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM