Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - CoreData NSPredicate - Fetch Children of parent

I'm trying to fetch all the children of a parent.

In my case the parent is an entity AgendaEvent which has many AgendaDate (the children).

so Here's my function:

 func getRelatedAgendaEvent(event: AgendaEvent) ->NSFetchRequest<AgendaDate> {
    // create a fetch request that will retrieve all the AgendaDate.
    let fetchRquest = NSFetchRequest<AgendaDate>(entityName: "AgendaDate")

    // set the predicate to only keep AgendaDate related with the AgendaEvent selected
    fetchRquest.predicate = NSPredicate(format: "parent == %@", event)

    return fetchRquest
}

and I use this in didselectRow for a tableView:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    var eventToPass: AgendaEvent!
    var eventDateToPassArray: [AgendaDate]!

    eventToPass = myTempEvents[indexPath.row]
    eventDateToPassArray = try! context.fetch(getRelatedAgendaEvent(event: eventToPass))
    DispatchQueue.main.async { () -> Void in
        self.performSegue(withIdentifier: "EventToModify", sender: eventToPass)
    }
}

}

I'm trying to use eventDateToPassArray in a segue. The error i'm getting is:

keypath parent not found in entity <NSSQLEntity AgendaDate id=1> with userInfo of (null)

I'm not sure this is the right path. I am trying to update a NSSet (AgendaDate) when the user edit an AgendaEvent. So basically while updating and AgendaEvent the user also updates the date in the related AgendaData NSSet.

Thank you!

-------------UPDDATE

Martin you mean this:

AgendaDate+CoreDataProperties.swift

extension AgendaDate {

@nonobjc public class func fetchRequest() -> NSFetchRequest<AgendaDate> {
    return NSFetchRequest<AgendaDate>(entityName: "AgendaDate")
}

@NSManaged public var agendaDates: NSDate?
@NSManaged public var agendaEvents: AgendaEvent?

}

AgendaDate+CoreDataClass.swift

import Foundation
import CoreData

@objc(AgendaDate)
public class AgendaDate: NSManagedObject {

}
like image 467
Marco Avatar asked Oct 30 '22 01:10

Marco


1 Answers

The key path used in the fetch request must match the actual name of the Core Data relationship, in your case "agendaEvents", there is no implicit "parent" relationship:

fetchRquest.predicate = NSPredicate(format: "agendaEvents == %@", event)

Even better, use #keyPath and the %K expansion

fetchRquest.predicate = NSPredicate(format: "%K == %@",
                                    #keyPath(AgendaDate.agendaEvents), event)

so the that compiler checks the validity of the key path. This helps to avoid using unknown key paths or typos.

Note that a better relationship name would be "agendaEvent" or just "event", with the singular form for a to-one relationship.

like image 165
Martin R Avatar answered Nov 15 '22 06:11

Martin R