Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data fetching with objectID

I have 2 entities in my data model as the images below:

Product:
Product

Attendance:
Attendance

I'm saving products with attendance relationship well! Now, I need to fetch the Products with a specific Attendance.objectID

I'm trying the following code:

func fetchProducts() {
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    
    let managedContext = appDelegate.managedObjectContext
    
    let fetchRequest = NSFetchRequest(entityName: "Product")
    let attendancePredicate = NSPredicate(format: "attendance.objectID == \(currAttendance.objectID)")
    fetchRequest.predicate = attendancePredicate
    
    print("Att = \(currAttendance.name!)")
    viewTypeSKU.hidden = true
    
    do {
        let results = try managedContext.executeFetchRequest(fetchRequest)
        products = results as! [NSManagedObject]
    } catch let error as NSError {
        print("Could not fetch \(error), \(error.userInfo)")
    }

}

I'm getting error: 'Unable to parse the format string "attendance.objectID ==

like image 266
sdadsad Avatar asked Oct 27 '25 10:10

sdadsad


1 Answers

Inside the fetch SELF is comparable to NSManagedObjectID and to the NSManagedObject. However you cannot do .objectID on the item being fetched. My theory is this is because when doing the . it is looking for attributes and/or relationships for the specific entity where .objectID is part of NSManagedObject. I could be wrong though.

However, if you just switched your NSPredicate to one of these it will work.

NSPredicate(format: "attendance == %@", currAttendance.objectID)

or

NSPredicate(format: "attendance == %@", currAttendance)

like image 85
boidkan Avatar answered Oct 28 '25 22:10

boidkan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!