tezvyn:

Optimize a slow NSFetchedResultsController screen

AI-drafted, machine-checkedSource: interviewadvanced
WHAT IT TESTS

Core Data fetch tuning.

OUTLINE

set fetchBatchSize so rows load in pages, use relationshipKeyPathsForPrefetching to avoid per-row faulting round trips, and add indexes matching sort and predicate to make queries fast.

WHAT THIS TESTS This checks deep Core Data knowledge: do you understand faulting, batching, and the SQLite layer beneath, and can you target the real bottleneck rather than the UI? It is a senior-level performance question.

A GOOD ANSWER COVERS Start by profiling with the Core Data Instruments template and the SQL debug flag to see how many queries fire. fetchBatchSize tells Core Data to fetch object identifiers up front but materialize rows in pages of the given size as they are accessed, so a list of ten thousand items does not load all at once, cutting memory and initial latency. relationshipKeyPathsForPrefetching addresses the N plus one problem: without it, accessing each row's relationship, such as a post's author, fires a separate fetch as the fault fires, causing one query per visible row; prefetching batch-loads those related objects in one round trip. Compound and single-column indexes on the attributes used in the fetch request's predicate and sort descriptors let SQLite use an index instead of scanning the whole table, which is critical when sorting or filtering large datasets. Other levers include setting returnsObjectsAsFaults appropriately, fetching only needed properties, and doing fetches on a background context.

COMMON WRONG ANSWERS Optimizing cell reuse while the slowness is unindexed SQL or per-row faulting. Setting an enormous fetchBatchSize that defeats paging. Forgetting that accessing relationships in cellForRow triggers hidden fetches.

LIKELY FOLLOW-UPS What is a fault and when does it fire? Why does the N plus one problem happen here? How does a compound index help a multi-key sort? Should heavy fetches run on a background context?

ONE CONCRETE EXAMPLE A feed lists ten thousand posts sorted by date and shows each author's name. Scrolling stutters because each cell faults the author relationship, firing thousands of queries, and the date sort scans the table. Setting fetchBatchSize to fifty, adding author to relationshipKeyPathsForPrefetching, and indexing the createdAt column collapses the work into a few batched, index-backed queries and smooths scrolling.

Read the original → developer.apple.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.