簡體   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