user8105388
user8105388

Reputation:

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). I added both view controllers for saving and displaying.

        import UIKit
import CoreData

class ViewController: UIViewController {

@IBOutlet var j1 : UITextField!
@IBOutlet var j2 : UITextField!


@IBAction func save(){

    let appD = UIApplication.shared.delegate as! AppDelegate

    let context = appD.persistentContainer.viewContext
    let entity = NSEntityDescription.entity(forEntityName: "Team", in : context)!

    let theTitle = NSManagedObject(entity: entity, insertInto: context)
    theTitle.setValue(j1.text, forKey: "score")
    theTitle.setValue(j2.text, forKey: "alba")


    do {
        try context.save()
    }
    catch {
        print("Tom Corley")

    }
}}
class twoVC: UIViewController {

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

        var itemsName : [NSManagedObject] = []
      var itemsName2 : [NSManagedObject] = []
    override func viewDidLoad() {
        super.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)
            if let score = itemsName[0].value(forKey: "score") {
                j1.text = (score as! String)
            }
            if let alba = itemsName2[0].value(forKey: "alba") {
                j2.text = (alba as? String)
            }


        }catch {
            print("Ashley Tisdale")
        }
    }}

Upvotes: 0

Views: 1763

Answers (2)

Joakim Danielson
Joakim Danielson

Reputation: 52013

Loop over the result from the fetch and append to a string that is then used as value for the label, this goes inside the do{...} where you do the fetch today. Note that I am only using one fetch request here.

itemsName = try context.fetch(fetchRequest)
var mergedScore: String = ""
var mergedAlba: String = ""
for item in itemsName {
    if let score = item.value(forKey: "score") as? String {
         mergedScore.append(score)
         mergedScore.append(" ") //separator
    }
    if let alba = item.value(forKey: "alba") as? String {
         mergedScore.append(alba)
         mergedScore.append(" ") //separator
    }
}
j1.text = mergedScore
j2.text = mergedAlba

Upvotes: 1

Nikunj Kumbhani
Nikunj Kumbhani

Reputation: 3924

Try this one it's Working for me Swift 4 I think You need to store the value as int which are used as sortDescriptor.

func FetchManagedObjectFromDatabaseForStoreData(Entity :NSEntityDescription) -> 
[NSManagedObject]
{
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>()

    // Add Sort Descriptor
    let sortDescriptor = NSSortDescriptor(key: "order", ascending: true)
    let sortDescriptor1 = NSSortDescriptor(key: "is_favourite", ascending: false)

    fetchRequest.sortDescriptors = [sortDescriptor,sortDescriptor1]

    // Create Entity Description
    fetchRequest.entity = Entity

    let result : [NSManagedObject] = []

    // Execute Fetch Request
    do{
        let result = try appDelegate.managedObjectContext.fetch(fetchRequest) as! [NSManagedObject]

    if  result.count > 0
    {
        return result

    }
    else
    {
        // return result

    }
}
catch{
    let fetchError = error as NSError
    print(fetchError)
}

return result
}

For Fetch Data

// Create Entity Description
let entityDescription = NSEntityDescription.entity(forEntityName: "Your Entity Name Here", in: appDel.managedObjectContext)

let DataObject = FetchManagedObjectFromDatabaseForStoreData(Entity: entityDescription!)

//Convert  Array of NSManagedObject into array of [String:AnyObject]     
for item in DataObject{

    let keys = Array(item.entity.attributesByName.keys)

    // Here is your result
    print((item.dictionaryWithValues(forKeys: keys) as NSDictionary).value(forKey: "id") as Any) // And so On Whatewer you Fetch

}

Upvotes: 0

Related Questions