我的数据库类中有一个方法可以验证给定值是否存在于实体中。除了我正在尝试优化此方法外,一切都运行良好。你们能告诉我这段代码是否可以进一步优化吗?
- (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;
}
干杯