简体   繁体   中英

CoreData search too slow

I am working on an iPhone app that searches through 91,000 entries. I am using CoreData, which works beautifully, except that it takes about 2 seconds to create the table of data. I have programmed it to do the search in the background, and added a spinner, but the user experience is still not ideal. I tried using FMDB which worked fine but wasn't any faster.

Essentially, I created my xcdatamodel in swift, added my entries to it, which works fine. (The code below is typed freehand, so sorry if there are typos)

I then create an NSFetchedResultsController:

let moc =(UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
searchText: String? = "name contains[c] \"seachText\""
nsfr = NSFetchRequest(entityName: "Example")
nsfr.fetchBatchSize = 20
nsfr.predicate = NSPredicate(format: searchText!)
nsfrc = NSFetchedResultsController(fetchRequest: nsfr, managedObjectContext: moc, sectionNameKeyPath: "section", cacheName: nil)

Then in my UITableViewController class (which conforms to NSFetchedResultsControllerDelegate):

nsfrc.delegate = self
nsfrc.performFetch()
self.tableView.reloadData()

Is there any way to speed up requests, like hashing the database? Any way to narrow search to the start of words? My data includes thousands of sentences, and I want to be able to search for parts of strings within. For example, "laz fo" should find "The lazy brown fox". Right now "azy own" will also find the string, which is not necessary. Any help would be appreciated! Even cutting the time in half would be wonderful.

FRC should perform very well with 100K records. However, string parsing is expensive, so depending on your data there could be performance issues.

You can try optimizing by replacing CONTAINS with BEGINSWITH although that will only match the beginning of the entire name string.

Alternatively, you can create a new entity Word and put them into a to-many relationship of Example (eg titleWords ) and use a predicate like

NSPredicate(format: "ANY titleWords BEGINSWITH[c] %@", searchTerm)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM