I'm working in a subclass of NSViewController
where in viewDidLoad
I fetch my entities from CoreData
as below:
let delegate = AppDelegate.init()
let context = delegate.persistentContainer.viewContext
let fetch = PicPathEntity.entityFetchRequest()
var tempEntities: [PicPathEntity] = []
context.performAndWait {
tempEntities = try! fetch.execute()
}
entities = tempEntities
Then during the itemForRepresentedObjectAt
function, it appears that the count of entities is the same, but the property values have become nil
/empty.
I did some searching and found similar problems with no clear answers (at least not for Swift
)
I can't seem to find information on how to properly fetch and retain the data in my entities variable.
答案 0 :(得分:0)
在阅读了对象与上下文之间的关系后,我想出了解决方法。
原来我要做的就是将上下文设为ViewController
的属性,而不是viewDidLoad
的局部变量。
var entities: [PicPathEntity] = []
var context: NSManagedObjectContext!
override func viewDidLoad() {
super.viewDidLoad()
let delegate = AppDelegate.init()
context = delegate.persistentContainer.viewContext
let fetch = PicPathEntity.entityFetchRequest()
context.performAndWait {
entities = try! fetch.execute()
}
}
由于对此答案有帮助,我现在将代码更新为:
var entities: [PicPathEntity] = []
var context: NSManagedObjectContext!
override func viewDidLoad() {
super.viewDidLoad()
let delegate = NSApplication.shared.delegate as! AppDelegate
context = delegate.persistentContainer.viewContext
let fetch = PicPathEntity.entityFetchRequest()
context.perform {
self.entities = try! fetch.execute()
self.picFinderEntityCollectionView.reloadData()
}
configureCollectionView()
}