Search code examples
iosobjective-ccore-datanspredicatensfetchrequest

Fetch and locally filter NSArray or execute fetchRequest multiple times


I need to count no. of objects from a collection in core data of that satisfy a certain criteria.

(eg. count no. employees with distinct departments).

There are two solutions to my problem:

  • (1) Fetch the collection in only one request and filter the array locally for each department using NSPredicate

  • (2) Execute multiple NSFetchedRequests directly on the data

Question is which solution will be fastest and take up least amount of memory given this is only for instrumentation purpose and is of no importance in the app in terms of behavior/UI.

Counter Question : If it is (1) - which is the best way to filter the array? manual looping and counting or NSPredicate?

P.S:

a. Names of departments are known to me. (its actually an enum)

b. collection is small - will be max 50


Solution

  • 1 is fastest and takes most memory. 2 will use the least memory but may take longer.

    However, this is not always true. In the event that your number of individual fetch requests will contain many of the same employee data sets that other fetch requests will return too, then it may even be the other way around. But as you are fetching for departments, that will not be the case.

    For a small collection it may not be much of a difference anyway.

    Counting question: This, too, depends. However, I'd go for the predicate as that is save for future use if the collection grows.