user12346
user12346

Reputation: 107

Fetch specific attributes from coredata swift

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,

Upvotes: 6

Views: 10650

Answers (2)

Gurjinder Singh
Gurjinder Singh

Reputation: 10329

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

Upvotes: 5

mrfour
mrfour

Reputation: 1268

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()
}

Upvotes: 10

Related Questions