2013-02-26 41 views
0

我在我的數據庫類中有一個方法,用於驗證給定的值是否存在於實體中。除了我正在試圖優化這種方法之外,一切工作都很好。你們可以讓我知道這個代碼是否可以進一步優化?提高核心數據重複驗證的效率

- (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; 
} 

乾杯

回答

1

我有兩個建議:

  • 測試在你的斷言確切平等"%K == %@",而不是"%K LIKE %@"

LIKE比較使用簡單的通配符(*?),從而例如搜索「Ĵ*」也將找到的條目「約翰」。這比測試平等要慢,可能不是有意的。

  • 創建該屬性的索引。

如果您必須非常快地搜索某些屬性,則可以在覈心數據檢查器中爲該屬性設置「索引」屬性。

注:注意countForFetchRequest:回報NSNotFound如果執行請求的錯誤,所以你也應該檢查該返回值。

+0

謝謝@Martin。我確實看到了性能的顯着提高:) – iSee 2013-02-27 01:59:59