In my swift code below I am trying to save a string into core data using a helper class. Right now my code is causing a runtime error stating Cannot assign value of type 'Data' to type 'String?' at imageInstance.text = data. I did something similar trying to save a image and it worked. I also added a core data photo
class DataBaseHelper {
static let shareInstance = DataBaseHelper()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
func saveText(data: Data) {
let imageInstance = Info(context: context)
imageInstance.txt = data
do {
try context.save()
print("text is saved")
} catch {
print(error.localizedDescription)
}
}
}
BASE CLASS
class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
DataBaseHelper.shareInstance.saveText(data: "Jessica")}
CodePudding user response:
Please be more careful how you name your functions.
You are going to save Text( so the parameter label data
is misleading and the type Data
is wrong.
Replace
func saveText(data: Data) {
with
func saveText(data: String) {
or – more meaningful because text
is already a part of the function name
func saveText(_ string: String) {
let imageInstance = Info(context: context)
imageInstance.txt = string
and call it
DataBaseHelper.shareInstance.saveText("Jessica")