我遇到了试图附加一个称为 products
的核心数据实体的问题 - 我使用了与添加companies
相同的代码,该代码正常。该应用程序的唯一区别在于,我想您可以说的公司只有一个"静态"桌面视图,而产品的表观视图是动态设置的,具体取决于利用哪个公司单元格。但是我不确定这将导致问题。
从昨天开始,我一直在应用程序上调试/检查值,似乎无论我尝试更改什么,products.count
中的CC_3保留0
。
我调用一个名为 handleSave()
的函数,当用户在三个文本字段中输入新值后命中完成按钮时,就像我的其他对象companies
:
func handleSave() {
guard let newProductUrl = NSURL(string: urlTextField.text!) else {
print("error getting text from product url field")
return
}
guard let newProductName = self.nameTextField.text else {
print("error getting text from product name field")
return
}
guard let newProductImage = self.logoTextField.text else {
print("error getting text from product logo field")
return
}
self.productController?.save(name: newProductName, url: newProductUrl as URL, image: newProductImage)
let cc = UINavigationController()
let companyController = CompanyController()
viewController = companyController
cc.viewControllers = [companyController]
present(cc, animated: true, completion: nil)
}
然后将save
函数称为附加products
:
func save(name: String, url: URL, image: String) {
guard let appDelegate =
UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext =
appDelegate.persistentContainer.viewContext
let entity =
NSEntityDescription.entity(forEntityName: "Product",
in: managedContext)!
let product = NSManagedObject(entity: entity,
insertInto: managedContext)
product.setValue(name, forKey: "name")
product.setValue(url, forKey: "url")
product.setValue(image, forKey: "image")
do {
try managedContext.save()
products.append(product)
} catch let error as NSError {
print("Could not save. (error), (error.userInfo)")
}
tableView.reloadData()
}
,数据在viewWillAppear
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard let appDelegate =
UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext =
appDelegate.persistentContainer.viewContext
let companyToDisplay = self.navigationItem.title!
let fetchRequest =
NSFetchRequest<NSManagedObject>(entityName: "Product")
fetchRequest.predicate = NSPredicate(format:"company.name == %@",companyToDisplay)
do {
products = try managedContext.fetch(fetchRequest)
print(products)
} catch let error as NSError {
print("Could not fetch. (error), (error.userInfo)")
}
}
当使用此完全相同的过程添加companies
时,新公司将出现在TableView中。但是现在使用产品,事实并非如此;表观视图保持空。我不确定区别是什么,我对核心数据的经验不够,我觉得我可以弄清楚问题所在。
非常感谢任何可以解决这个问题的人!
调用handleSave()
&amp;在执行table.reloadData()
之前,您需要在viewWillAppear()
中执行DB提取操作。
将您的 fetchRequest
逻辑从 viewWillAppear()
划分为称为(SAS) fetchUpdatedData()
的函数。
现在,在try managedContext.save()
之后,执行fetchUpdatedData()
,更新您的product
数据数组&amp;然后由table.reloadData()
使用 NSFetchedResultsController
与模型保持同步。NSFetchedResultsController
监视Core -data并在有更新时发送委托消息 - 然后您可以更新tableview。否则,每当核心数据更改时,都必须手动进行刷新。