Search code examples
swiftmagicalrecord

I am trying to fetch latest added data from Magical Records


I am trying to fetch latest added data from Magical Records. I have one entity called weighttrack and it has two attributes- weight and date and I want to fetch latest added dates weight to my label so how could it possible?

class WTStatusVC: UIViewController {
    var WeightArray = [WeightTracker]()
    var tsk: WeightTracker?
    @IBOutlet weak var currentWeightLbl: UILabel!
    @IBOutlet weak var previousWeightLbl: UILabel!

    override func viewWillAppear(_ animated: Bool) {
        super .viewWillAppear(animated)

        if let data = WeightTracker.mr_findAll(with: NSPredicate(format: "date == %@", "\(String(describing: tsk?.date))")) as? [WeightTracker] {

            WeightArray = data
            DispatchQueue.main.async {
               self.currentWeightLbl.text = self.tsk?.weight
            }
            print(data)
    }
}

Solution

  • You can do it with Filter

    self.WeightArray = self.WeightArray.filter({ (item) -> Bool in
                   return item.date == tsk?.date   
           })