简体   繁体   中英

Cannot convert value of type 'String' to expected argument type 'NSManagedObject' Swift

I was wondering why I can't add my data from Core Data to my tableview. It was first added and stored but when the app is reloaded the data is gone so I need to reload it but I can't seem to add the data to my tableview? Here is the code

var titlename: [NSManagedObject] = []

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let manageContext = appDelegate.persistentContainer.viewContext
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Items")

    fetchRequest.returnsObjectsAsFaults = false

    do {
        let results = try manageContext.fetch(fetchRequest)

        for result in results as! [NSManagedObject] {
            if let theName = result.value(forKey: "name") as? String {
                titlename.append(theName)
            }
        }
    } catch let error as NSError {
        print("Could not fetch. \(error), \(error.userInfo)")
    }

    tableView.reloadData()
}

您可能需要将titleName类型更改为

 var titlename: [String] = []

If tableview use NSManagedObject for create cell the simply add NSManagedObject data to the array.

for result in results as! [NSManagedObject] {
         titlename.append(result)
    }

OR

The tableview only use the string from titlename array for creating cell then just change the type NSManagedObject to String .

var titlename: [String] = []

This will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM