![](/img/trans.png)
[英]Get property from NSCoder in required init(coder aDecoder: NSCoder)
[英]UITableView “cellForRowAt: indexPath” Occasionally Calling “init?(coder aDecoder: NSCoder)” on Core Data Attribute
我有一個核心數據實體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
}
}
我在UITableViewCell
顯示Person
實例的age
。 此實例( person
)的年齡值為10.0,即person.age.value = 10.0
,這樣當通過UIStepper
以編程方式更改scale = 2.0
以表示scale = 2.0
, UITableViewCell
顯示20.0
(即scale * value
)。
但是 ,我發現如果我增加UIStepper
足夠的次數,最終會在tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
方法中調用Person
的Age
類的初始化,該方法返回一個實例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.