ma11hew28
ma11hew28

Reputation: 126367

Core Data fetch last 50 objects?

Like the native iPhone Messages app, I want to code AcaniChat to return the last 50 messages sorted chronologically. Let's say there are 200 messages total in Core Data.

I know I can use fetchOffset=150 & fetchLimit=50 (Actually, do I even need fetchLimit in this case since I want to fetch all the way to the end?), but can I fetch the last 50 messages without first having to fetch the messages count? For example, with Redis, I could just set fetchOffset to -50.

Upvotes: 0

Views: 370

Answers (1)

Jody Hagins
Jody Hagins

Reputation: 28409

Reverse the sort order, and grab the first 50.

EDIT

But then, how do I display the messages in chronological order? I'm using an NSFetchedResultsController. – MattDiPasquale

That wasn't part of your question now, was it ;-)

Anyhow, the FRC is not used directly. Your view controller is asked to provide the information, and it then asks the FRC. You can do simple math to transform section/row to get the reverse order.

You could also use a second array internally that has a copy of the objects in the FRC, but with a different sort ordering. That's simple as well.

More complex, but more "academically interesting" is using a separate MOC with custom fetch parameters.

However, before I went too far down either path, I'd want to know what's so wrong with querying the count of objects. It's actually quite fast.

Until I had proof from Instruments that it's the bottleneck that's killing my app, I'd push for the simplest solution possible.

Upvotes: 3

Related Questions