Piyush
Piyush

Reputation: 188

Searching in an entire entity, Core Data

In my core data model, I want to search an entity which has one to one relationship with other entities and has in all 10 attributes. If a keyword appears anywhere in the entity (even in the child entity), I should be able to print the same entity.

Using enumeration block, doesn't look like a good option to me.

How should I put a search in place without compromising on the performance?

Upvotes: 1

Views: 126

Answers (2)

Bravendary
Bravendary

Reputation: 113

Actually if you go back with the Fast Enumeration, and use rangeOfString like this:

NSString * lowerCaseTerm  = [term lowercaseString];    
NSString * content = [(NSString*)[theEntity valueForKey:"key"] lowercaseString];

BOOL containsWord = [content rangeOfString:lowerCaseTerm].location == NSNotFound ? false : true;

Where "content" is the "NSString" that you're looking for in the entity, you will get better performance than NSPredicate. Predicate is more elegant (much less code) but its much slower than rangeOfString.(Will require some set up)

If you want to look into multiple keys for an entity then set up a quick array and loop over that. @[@"key1",@"key2"];

I used this method for not only finding if an entity contained a word but also determined relevance. With NSPredicate it took 7 seconds to search 2000+ entities and filter out the ones not needed then resort.

Where with rangeOfString everything took about 0.25 seconds. 0.5 seconds on secondary thread. (Instruments reporting for my specific case. I needed to provide a weighted relevancy to order by for customer satisfaction.)

(Hint: finding the word in the content is where the hangup was)

Naturally you will want to use a secondary thread to prevent your UI from locking up while you perform this operation. If more clarity is needed please do tell me.

Upvotes: 1

Anton
Anton

Reputation: 139

Try use NSPredicate where you can write a keyword and the name of entity in NSFetchRequest

Upvotes: 2

Related Questions