In order to accelerate CoreData search. An indexing is going to be needed.
The improvement of speed from my experience is 10 times faster from 3 seconds to 0.3 second out of 100,000 items.
Unfortunately, Apple has no document on indexing with CoreData and the WWDC tutoring has very few info of this.
Some easy setup first:
- Add Fetch Index from long pressing the button “Add Entity” in the editor of .xcdatamodeld file.
- Edit the Fetch Index title to “
yourIndexName
” - Add property on the right side of it.
4. IMPORTANT!! Select on the Fetch Index from the left side and change the type from Binary
to R-Tree
on the right panel. This is the key to massive acceleration.
5. Change the Hash Modifier on the bottom of the editor to any kind of String
by selecting the table you are editing.
After I tried the CoreData indexing. The very confusion of mine is
What is the syntax?
The predicate of CoreData Index should be:
NSPredicate(format: “indexed:by:(indexField,’yourIndexName’) between {%i,%i}”, fromValue, toValue)
The “fromValue” and “toValue” can be the same value if you’re trying to find a match.
The Database will looks like this after we setup the CoreData indexing:
The Z_PK
is the original ID in the original table of the row.
The ZTYPE_MIN
and ZTYPE_MAX
is auto-generated by Xcode. For my case the row is an Int
type, so the min and max is the value of that Int
That’s it! Please feel free to ask or correct any mistake from my article by leaving a message.