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

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



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")






You are getting this error because itemsName and itemsName2 are array and there is no String init available that accept array as argument, can you please give more detail of what you want that can help us to understand what you want
– Nirav D
Aug 6 at 14:15


itemsName


itemsName2





@NiravD I am trying to call 2 different arrays from core data and display them on separate labels. The core Data Strings are alba and score.
– Sam Burns
Aug 6 at 16:02





You are still not getting, what i'm saying is how can you display array in label also the array is type of NSManagedObject, can you show your Team entity
– Nirav D
Aug 7 at 6:51



NSManagedObject





@NiravD I updated my question with all of my code. That should answer your question.
– Sam Burns
Aug 8 at 4:06





Now you are setting value from first object but your app may crash if your array is empty if you want to show all the data what you need is to use tableView search about it and you will know how to implement it
– Nirav D
Aug 8 at 5:21





2 Answers
2



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.


do...


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





What function do I put this in?
– Sam Burns
Aug 7 at 13:27





The one in your question , replace the existing lines with it
– Joakim Danielson
Aug 7 at 13:29






Its starting to work but Its only displaying the first index. I want to display everything in the array.
– Sam Burns
Aug 7 at 13:36





@SamBurns I intentionally only read the first value in my answer because I didn’t know exactly what you wanted. Do I understand it correctly that you want to add all fetched values to the label?
– Joakim Danielson
Aug 7 at 14:19





I want to fetch all of the values to the label.
– Sam Burns
Aug 7 at 20:53



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






I am confused on what to put in result.count >0. I tried itemsName = try context.fetch(fetchRequest) itemsName2 = try context.fetch(fetchRequest2) j1.text = String(itemsName) j2.text = String(itemsName2) but I am getting the same error.
– Sam Burns
Aug 6 at 13:26





@SamBurns Here itemsName and itemsName2 is not String type it's NSManagedObject so you need to convert it same like I have done in an Updated answer. Try it :)
– Nikunj Kumbhani
Aug 7 at 4:15






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

make 2 or more post in bootsrap

Store custom data using WC_Cart add_to_cart() method in Woocommerce 3

Firebase Auth - with Email and Password - Check user already registered