Reputation: 604
I have a method in my Database class that verifies whether the given value exists in a entity or not. Everything is working perfectly fine except that I am trying to optimise this method. Can you guys let me know whether this code can be further optimised?
- (NSUInteger)recordAlreadyExists:(NSString*)string forEntity:(NSString*)entityName forKey:(NSString*)key
{
NSManagedObjectContext *newContext = [Helper generateNewContext];
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:newContext];
[newContext setUndoManager:nil];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
[fetchRequest setEntity:entity];
[fetchRequest setFetchLimit:1];
//NSString *predicateString = [NSString stringWithFormat:@"%K LIKE \"%@\"", key, string];//,key,string];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K LIKE %@", key, string];
[fetchRequest setPredicate:predicate];
NSError *error;
NSUInteger resultsCount = [newContext countForFetchRequest:fetchRequest error:&error];
if(resultsCount)
return resultsCount;
return 0;
}
Cheers
Upvotes: 0
Views: 103
Reputation: 539945
I have two suggestions:
"%K == %@"
in your predicate, instead of "%K LIKE %@"
.LIKE
compares using simple wildcards (*
, ?
), so that for example searching for "J*" will also find an entry "John". This is slower than testing for equality and probably not intended.
If you have to search for some attributes very fast, you can set the "Indexed" property in the Core Data inspector for that attribute.
Remark: Note that countForFetchRequest:
returns NSNotFound
if there is an error executing the request, so you should also check for that return value.
Upvotes: 1