我遇到CoreData问题,我在AppDelegate中设置了一些数据。然后在视图控制器的类中,我获取这些值并在列表视图中显示它们。当我尝试从CoreData中获取视图中的值时,我得不到任何回报。
这是我用来创建上下文的代码:
public func createMainContext() -> NSManagedObjectContext {
let modelUrl = Bundle.main.url(forResource: "ItemModel", withExtension: "momd")
guard let model = NSManagedObjectModel.init(contentsOf: modelUrl!) else { fatalError("model not found") }
let psc = NSPersistentStoreCoordinator(managedObjectModel: model)
try! psc.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: nil)
let context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
context.persistentStoreCoordinator = psc
return context
}
这是我用来获取值的代码:
var fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Topic")
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = createMainContext()
let result = try! context.fetch(fetchRequest)
debugPrint("---- \(result)")
插入新实体
let context = self.createMainContext()
let entity = NSEntityDescription.insertNewObject(forEntityName: "Topic", into: context)
entity.setValue(name.stringValue, forKey: "name")
当我最初设置值时,我会执行fetch&amp;但是,我可以看到这些值,当从另一个视图执行提取时,我什么也得不到。
有人对我做错了什么或者正确的方法有建议吗?
由于