Fetch core data string and place in a label (Swift4)

I am trying to call 2 different core data strings and place them each on separate labels. Right now I am getting the error Cannot invoke initializer for type ‘init(_:)’ with an argument list of type ‘([NSManagedObject])’. This error is coming from j1.text = String(itemsName).

                class twoVC: UIViewController {

@IBOutlet var j1 : UILabel!
@IBOutlet var j2 : UILabel!

    var itemsName : [NSManagedObject] = []
  var itemsName2 : [NSManagedObject] = []
override func viewDidLoad() {
    // Do any additional setup after loading the view, typically from a nib.

    let appD = UIApplication.shared.delegate as! AppDelegate

    let context = appD.persistentContainer.viewContext

    let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Team")
    fetchRequest.sortDescriptors = [NSSortDescriptor(key: "score", ascending: true)]

    let fetchRequest2 = NSFetchRequest<NSManagedObject>(entityName: "Team")
    fetchRequest.sortDescriptors = [NSSortDescriptor(key: "alba", ascending: true)]

    do {
        itemsName = try context.fetch(fetchRequest)
        itemsName2 = try context.fetch(fetchRequest2)
        j1.text = String(itemsName)
        j2.text = String(itemsName2)

    }catch {
        print("Ashley Tisdale")

@timswift Thanks very much for your question!

The first thing I would tell you is to check to see if your fetch function is in fact returning results. If you are not receiving any objects from your request, naturally you’ll have problems going forward.

One glaring error I do see is that you are trying to convert an array of NSManagedObjects into a single String object, which you can’t do. If your fetchRequest is indeed working, and returning results to you, then extract the object you want from the array, and then assign the property (which I assume is of type String) of that object, and assign it to the text property of your UILabel. That probably is your issue. :slight_smile:

I hope this helps!

All the best!

This topic was automatically closed after 166 days. New replies are no longer allowed.