我想将数据添加到我使用Core Data在另一个ViewController中创建的条目
这是我创建条目的地方: ViewController.swift
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let location:Location = NSEntityDescription.insertNewObject(forEntityName: "Location", into: DatabaseController.persistentContainer.viewContext) as! Location
location.title = "Statue of Liberty"
}
现在在我的数据库中有更多我想要添加的信息并保存在名为“LocationDetailController”的另一个ViewController中 . 我正在使用fetchRequest这样做 .
LocationDetailController
@IBOutlet weak var placeDescription:UITextView!
func setDescription(text:String){
loadDescription();
}
let fetchRequest:NSFetchRequest<Location> = Location.fetchRequest();
do{
let searchResult = try DatabaseController.persistentContainer.viewContext.fetch(fetchRequest)
print("number of results: \(searchResult.count)");
for result in searchResult as [Location]{
if result.title == "Statue of Liberty" {
//the text within the textfield is assigned to the dscr value received by the search
result.dscr = placeDescription.text;
DatabaseController.saveContext();
}
}
} catch{
print("Error: \(error)");
}
}
func loadDescription(){
let fr:NSFetchRequest<Location> = Location.fetchRequest();
do{
let searchResult = try DatabaseController.persistentContainer.viewContext.fetch(fr)
print("number of results: \(searchResult.count)");
for result in searchResult as [Location]{
if result.title == barTitle {
placeDescription.text = result.dscr;
}
}
} catch{
print("Error: \(error)");
}
}
只有程序没有终止时,这才有效 . 当我这样做时,似乎数据不存储在数据库中 . 如何访问我在第一个ViewController中创建的确切实体,以便为表提供其他信息?