I am looking for a way to get ranges of all occurrences of a string in a larger string in Core data.
My current solution involves finding all the objects that have atleast on occurrence and then doing the search again to generate the ranges of string. This method is not very efficient as it is loading a lot of persistent objects in the memory especially for small/single-char search keys.
I am looking for a way where I get ranges of all occurrences such that loading of all objects can be prevented.
Code that I am using
Following code gives me an array of all the objects that have atleast one occurence
let fetchRequest = Note.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "content contains[cd] %@", key)
return try container.viewContext.fetch(fetchRequest)
This is the code that gives me ranges of all occurrences
var ranges: [Range<String.Index>] = []
while let range = string.range(of: substring, options: [.caseInsensitive, .diacriticInsensitive], range: (ranges.last?.upperBound ?? string.startIndex)..<string.endIndex, locale: nil) {
if isCancelled { return }
ranges.append(range)
}