2013-05-07 55 views
1

我想從基於id的coredata中獲取記錄。因爲我在每次迭代中獲取for循環的執行時間非常大。有人能告訴我如何有效地做到這一點。Coredata在for循環中獲取

for (int i = 0; i < [tempCodeDescArray count]; i++) { 
     NSDictionary *codeDescDict = [tempCodeDescArray objectAtIndex:i]; 
     NSPredicate *predicate=[NSPredicate predicateWithFormat:@"itemId=%@",[codeDescDict valueForKey:@"itemId"]]; 
     [fetchRequest setPredicate:predicate]; 
     NSError *error=nil; 
     NSArray *result=[context executeFetchRequest:fetchRequest error:&error]; 
    } 
+0

你可以用另一種方式來完成 - >在一個FetchRequest中獲取所有數據,然後在結果上做一個循環,這使得它更快。訪問數據一次 – Omarj 2013-05-07 09:45:55

回答

5

創建要獲取所有ID的數組:

NSArray *idsToFetch = [tempCodeDescArray valueForKey:@"itemId"]; 

,並用一個單一的讀取請求獲取所有對象,使用謂語:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"itemId IN %@", idsToFetch]; 

(如果您需要這個來導入數據,我也可以推薦在「核心數據編程指南」中閱讀 Implementing Find-or-Create Efficiently。)

+0

偉大的解決方案只是想在這裏發佈相同的答案,所以,肯定這是最好的。 – 2013-05-07 09:49:15

+0

非常感謝您的回答 – Karthick 2013-05-07 10:50:10