I have a pretty simple little schema that looks like this:
Trail –> Segment –> Coordinate
All of the proper relationships are in place to make this work, and they certainly let me do something like this:
NSArray *trails = <query all trails>
for (Trail *trail in trails) {
for (Segment *segment in trail.segments) {
for (Coordinate *coordinate in segment.coordinates) {
//do something with coords
}
}
}
Coming from a Django background, I was delighted with this, and assumed the fewest possible queries would be run against sqlite3. Wrong! There is a query made for each and every object in these loops.
I’ve now read the Core Data documentation on faulting, I understand what’s going on, although I would really like to know what the best practices are for dealing with a situation like this. I need every single object in memory (the coords model has ~100,000 objects) because they are all used at one moment to plot a trail on a map.
How should I deal with this ultra lazy loading?
You could use the
setRelationshipKeyPathsForPrefetching:method ofNSFetchRequestfor this. From the documentation:So in your initial fetch request for the trails you could add
(I never tried this with 2 levels deep, only with one level.)