How to use a nspredicate in textfieldidendediting

My swift code below uses textFieldDidEndEditing as a way to fetch a string saved into coredata. So if the user enters 1 the first entry that was saved into core data should abppear the label labelName. That is all that should happen I just dont know how to user the nspredicate listed below. Look at func textFieldDidEndEditing.

            import UIKit
  import CoreData

   class ViewController: UIViewController,UITextFieldDelegate {
   @IBOutlet var labelName : UILabel!
     @IBOutlet var enterT : UITextField!

       // MARK: Variables declearations
     let appDelegate = UIApplication.shared.delegate as! AppDelegate //Singlton instance
     var context:NSManagedObjectContext!

    // MARK: View Controller life cycle methods
   override func viewDidLoad() {



    // MARK: Methods to Open, Store and Fetch data

    func textFieldDidEndEditing(_ textField: UITextField) {
 NSPredicate(format: "index == %ld", Int(enterT.text!) ?? 0)

   //use this to place the the first string from username on labelname if one is entered
    func openDatabse()
      context = appDelegate.persistentContainer.viewContext
      let entity = NSEntityDescription.entity(forEntityName: "Users", in: context)
    let newUser = NSManagedObject(entity: entity!, insertInto: context)
     let newUser2 = NSManagedObject(entity: entity!, insertInto: context)
     let newUser3 = NSManagedObject(entity: entity!, insertInto: context)
    saveData(UserDBObj: newUser, UserDBObj2: newUser2, UserDBObj3: newUser3)


    func  saveData(UserDBObj:NSManagedObject,UserDBObj2:NSManagedObject,UserDBObj3:NSManagedObject)
     UserDBObj.setValue("kim kardashian", forKey: "username")
     UserDBObj2.setValue("jessica biel", forKey: "username")
      UserDBObj3.setValue("Hailey Rienhart", forKey: "username")

         print("Storing Data..")
          do {
       } catch {
         print("Storing data Failed")


        func fetchData()
print("Fetching Data..")
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
request.returnsObjectsAsFaults = false
do {
    let result = try context.fetch(request)
    for data in result as! [NSManagedObject] {
        let userName = data.value(forKey: "username") as! String

        print("User Name is : "+userName)
} catch {
    print("Fetching data Failed")

@timswift Do you still have issues with this?

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