6

I am developing core data in my application. I want to fetch name attribute from the core data.

class ViewController: UIViewController {

@IBOutlet weak var saveDataBtn:UIButton!
@IBOutlet weak var dataTxtField:UITextField!
@IBOutlet weak var dataLbl:UILabel!
var tasks: [Task] = []
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

@IBAction func saveDataBtnPressed(_sender : UIButton){
    print("Save Data.")
    let task = Task(context: context)
    task.name = dataTxtField.text
    (UIApplication.shared.delegate as! AppDelegate).saveContext()
    getData()
}

func getData(){
    do{
        tasks = try context.fetch(Task.fetchRequest())

    }catch{
        print("Fetching Failed")

    }

}

I am attaching my xcdatamodel

How can i get it?

Thanks,

7
  • Fetch the Task object you're interested in and read its "name" property. Commented Oct 13, 2017 at 15:17
  • I have already fetch task object. but i am not able to read name property Commented Oct 13, 2017 at 15:19
  • Can you please let me know that how can i get the name property from task object Commented Oct 13, 2017 at 15:21
  • What does "i am not able to read name property" mean? You use task.name to set it, do you get an error if you read it the same way? Commented Oct 13, 2017 at 15:29
  • I got it. I was getting error before. Thank you :) Commented Oct 13, 2017 at 15:30

2 Answers 2

10

In Swift 4, you can access the property directly.

do {
    let tasks = try context.fetch(request)
    for task in tasks {
        print(task.name)
    }
} catch let error {
    print(error.localizedDescription)
}

UPDATED - How to delete and update an instance of an Entity.

Here are some ideas to organize the code to deal with the updating and deleting.

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

extension Task {
    // to get an instance with specific name
    class func instance(with name: String) -> Task? {
        let request = Task.fetchRequest()

        // create an NSPredicate to get the instance you want to make change
        let predicate = NSPredicate(format: "name = %@", name)
        request.predicate = predicate

        do {
            let tasks = try context.fetch(request)
            return tasks.first
        } catch let error {
            print(error.localizedDescription)
            return nil
        }
    }

    // to update an instance with specific name
    func updateName(with name: String) {
        self.name = name
        (UIApplication.shared.delegate as! AppDelegate).saveContext()
    }

    // to delete an instance
    func delete() {
        context.delete(self)
        (UIApplication.shared.delegate as! AppDelegate).saveContext()
    }
}

func howItWorks() {
   guard let task = Task.instance(with: "a task's name") else { return }
   task.updateName(with: "the new name")
   task.delete()
}
Sign up to request clarification or add additional context in comments.

2 Comments

Do you have an idea about to update and delete specific row in swift 4?
I have updated the answer. But I still suggest reading this, developer.apple.com/library/content/documentation/Cocoa/….
5

In Swift 4.1 and 5. We will use NSPredicate to specify our required condition. NSFetchRequest has a property predicate will set our predicate here as follow.

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext

    let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
    let predicate = NSPredicate(format: "username = %@", argumentArray: ["John"]) // Specify your condition here
// Or for integer value
// let predicate = NSPredicate(format: "age > %d", argumentArray: [10])

    fetch.predicate = predicate

    do {

      let result = try context.fetch(fetch)      
      for data in result as! [NSManagedObject] {
        print(data.value(forKey: "username") as! String)
        print(data.value(forKey: "password") as! String)
        print(data.value(forKey: "age") as! String)
      }
    } catch {
      print("Failed")
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.