LAST CHANCE: Save 50% on all my Swift books and bundles! >>

How to Create a Core Data First/Last-Only Predicate?

Forums > SwiftUI

Setup: I have a Core Data model in a SwiftUI app that has two entities, Book and Reading, with a one to many relationship such that a single book can have multiple entries in Reading for reading the book more than once. Both entities have a UUID attribute and some other attributes, and the one to many relationship is in place with the destinations and inverses. The Reading entity has a date attribute called startDate for when you start reading a book. I have a fetch request of Reading behind a List that lets you see a list of all your reading entries. That's all working great.

The Question: How do I create an NSPredicate for the Reading fetch request to return all reading entries that are either the first or last reading for a book based on the startDate?

The image has the Book and Reading entities at the top along with examples of the expected results at. the bottom with a first-only predicate and a last-only predicate. Without the predicate, it would return the full list of reading entries, which is already working fine. My feeling is that the first/last-only NSPredicate would be some kind of subquery with a sort on startDate, but I haven't been able to find a way to do this kind of request. Does anyone have a way of doing this?


Add an NSSortDescriptor to your NSPredicate to get the request sorted appropriately by startDate, then set the fetchLimit property of NSFetchRequest to 1.


Hacking with Swift is sponsored by Essential Developer.

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until July 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.