最近,我尝试向我的CoreData实体添加一个新属性,根据我的阅读,我应该通过Editor> Add Model Version创建一个新的.xcdatamodel模型版本。但是,由于我所做的所有尝试保存的数据都无法再保存,因此,我被告知应该将一个新的.xcdatamodeld文件添加到我的项目中,并且也没有发生。
从保存到加载,这是我与CoreData相关的所有代码:
保存:
@IBAction func SaveContact(_ sender: Any) {
let present = ContactS(context: managedObjectContext)
if (FN?.text != "" || LN?.text != "" || Email?.text != "" || Phone?.text != "" || Lease?.text != ""){
present.name = FN?.text
present.email = Email?.text
present.coments = Comments?.text
present.phone = Phone?.text
let imgData = Picture.image?.jpegData(compressionQuality: 1)
present.image = imgData
do {
try self.managedObjectContext.save()
}catch{
print("an error has occurred")
}else{
// this part is not important as it only prompts the user to fill out all text fields
}
}
正在加载:
var contact = [ContactS]()
func loadData(){
let contactRequest:NSFetchRequest<ContactS> = ContactS.fetchRequest()
do {
contact = try managedObjectContext.fetch(contactRequest)
self.TableView.reloadData()
}catch{
print("Error!")
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
self.TableView = tableView
return contact.count
}
func numberOfSections(in tableView: UITableView) -> Int {
self.TableView = tableView
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
self.TableView = tableView
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! TableClass
let contacts = contact[indexPath.row]
cell.Name.text = contacts.name
cell.Picture.image = UIImage(data: contacts.image!, scale: 1)
return cell
}