Here’s an example of my data model:
- There are mailboxes
- Each mailbox has many messages
- Each message has a flag to indicate if it is unread
How can I count the number of unread messages for a specific mailbox?
I tried creating a fetch request in the data model editor, but I can’t add a condition for the mailbox although the message entity has a relationship defined for its owning mailbox.
I know I’m not supposed to think in SQL when dealing with Core Data, but it feels so natural so say:
SELECT count(*) FROM Messages WHERE unread = 1 AND mailboxId = 12345
Is there another way to get the unread message count other than looping through each message for a specific mailbox?
You want to count without fetching the objects, as that would take longer:
Returns the number of objects a given fetch request would have returned if it had been passed to executeFetchRequest:error:
You will also need to add a predicate to your fetch request (which is the WHERE clause).
e.g
(I may have my predicate syntax wrong…. but you should get the idea)