Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,

like image 276
user12346 Avatar asked Dec 05 '22 13:12

user12346


1 Answers

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()
}
like image 155
mrfour Avatar answered Dec 23 '22 15:12

mrfour