NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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 Judo

SPONSORED Let’s face it, SwiftUI previews are limited, slow, and painful. Judo takes a different approach to building visually—think Interface Builder for SwiftUI. Build your interface in a completely visual canvas, then drag and drop into your Xcode project and wire up button clicks to custom code. Download the Mac App and start your free trial today!

Try 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.