访问CoreData属性时出现问题

时间:2017-10-06 13:00:09

标签: ios swift core-data

我在核心数据中保存了某个属性name,如此...

//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)")
}

现在我想在另一个viewcontroller中获取此name,以便我可以将其作为API调用中的参数传递。但我怎么能得到我无法弄清楚的名称属性。 另外,我不太擅长斯威夫特因此问这个问题......:)

1 个答案:

答案 0 :(得分:0)

你应该对 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")) } 进行一些很好的教程,因为这是一个非常基本的问题。在这里提问之前,我认为你没有用谷歌搜索过。我会给你解决方案,但不要再重复一次。

ng2-file-upload

<强>链接:

https://www.appcoda.com/introduction-to-core-data/

https://www.raywenderlich.com/145809/getting-started-core-data-tutorial

https://code.tutsplus.com/tutorials/core-data-and-swift-managed-objects-and-fetch-requests--cms-25068