0
嗨,我一直在使用核心数据来存储和检索核心数据中的一些值(仅字符串)。这是我如何存储值。核心数据值返回无
的功能:
public func saveStringValue(forKey: String, value: String) -> Bool{
var saved = false
if self.entityName != nil && self.appDelegate != nil{
let context = appDelegate?.persistentContainer.viewContext
if context != nil{
let entity = NSEntityDescription.entity(forEntityName: self.entityName!, in: context!)
let entityHandle = NSManagedObject(entity: entity!, insertInto: context!)
entityHandle.setValue(value, forKey: forKey)
do{
try context?.save()
saved = true
}catch let error as NSError{
saved = false
print("Error : \(error)")
}
}
}
return saved
}
这是我如何称呼它
let historyManager = HistoryManager(entity: "SearchHistory")
let titleInserted = historyManager.saveStringValue(forKey: "title", value: book.title!)
if(titleInserted == true)
{
print("Title Inserted to Entity")
}
if let image = book.imageUrl{
let imageInserted = historyManager.saveStringValue(forKey: "image", value: image)
if imageInserted == true{
print("Image Url Inserted to Entity")
}
}
我可以打印控制台看到
- 标题插入实体
- ImageInserted进入实体
这里是一个检索的核心数据存储值的代码
public func fetchAll() -> [Book]{
var books = [Book]()
let context = self.appDelegate?.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: self.entityName!)
//let fetchRequest: NSFetchRequest<SearchHistory> = SearchHistory.fetchRequest()
do{
let fetchedBooks = try context?.fetch(fetchRequest)
for aBook in fetchedBooks!{
if let title = aBook.value(forKey: "title"){
let book = Book(title: title as! String)
if let im = aBook.value(forKey: "image"){
book.imageUrl = im as! String
print("ImageUrl : \(im) : ")
}
else{
print("No Value for key : image")
}
books.append(book)
}
}
}
catch let error as NSError{
print("Fetch Error: \(error.localizedDescription)")
}
print("Books : \(books.count)")
return books
}
但是当我运行的代码来检索书IMAGEURL则返回nil并打印
- 密钥没有值:图片 它检索标题而不是imageUrl。 你能帮助我解决这个问题吗?或者指点我正确的方向。并且请张贴我为什么得到这个问题和如何解决它的原因。谢谢。
你为什么写让newHistory = SearchHistory(上下文:上下文)没有类SearchHistory。 –
是的,工作。谢谢。 –
除非您在核心数据模型中关闭此选项,否则Xcode会自动为您的Core Data实体创建类。 – Paulw11