问题与访问一CoreData属性
问题描述:
我节省一定的属性name
核心数据,像这样..问题与访问一CoreData属性
//Saving to CoreData
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Category", in: managedContext)
let category = NSManagedObject(entity: entity!, insertInto: managedContext)
category.setValue(name, forKeyPath: "theName")
do {
try managedContext.save()
self.mangObjArr.append(category as! Category)
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
现在我想要得到这个name
在另一个视图控制器,这样我可以把它作为一个API调用中的参数。但是,我如何才能获得我无法弄清楚的名称属性。 此外,我不是斯威夫特那么好,因此问的问题... :)
答
你应该Core Data
一些好的教程,因为这是一个非常基本的问题。在这里提出问题之前,我认为您没有使用Google搜索。我会给你解决方案,但不要再重复一遍。
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Category")
if let fetchedObjects = try? managedContext.fetch(fetchRequest), !fetchedObjects.isEmpty
{
let category = fetchedObjects.first as? NSManagedObject
print(category?.value(forKey: "theName"))
}
链接:
https://www.appcoda.com/introduction-to-core-data/
https://www.raywenderlich.com/145809/getting-started-core-data-tutorial
谢谢@ PGDev..your答案是非常有益的。还有一个问题(请原谅...... :))。我也从API响应获得'id'。但是这个ID在xcdatamodel中没有属性。那么我怎么把它保存在数据库中?我必须为这个“ID”做出另一个属性..?再次感谢... – bws
您必须为此创建一个新属性。任何值都将保存在与唯一属性对应的核心数据中的实体中。 – PGDev
好的...所以你说如果我想保存这个id,我将不得不写下在问题中提到的coredata方法中的完整保存,然后在你的答案中进行检索。 。? – bws