2011-06-04 94 views
3

我有一個200個數字(項目ID)數組,我想從每個項目的核心數據使用其項目ID獲取一些數據。我假設這樣做的唯一方法是在每次迭代中執行fetchRequest的循環中查詢核心數據,並將結果添加到可變數組中。這看起來像一個記憶豬,循環超過200個項目可能不是獲得我需要的數據的最佳方式。從核心數據循環陣列和提取數據

所有這些數據的目的地是一張表,所以我想使用NSFetchedResultsController,但是,這可能會要求太多。

當你有幾百個你想查詢的項目時,從核心數據中檢索數據的最佳方法是什麼?

說明性的代碼示例將不勝感激。

這裏是我的代碼:

- (NSFetchedResultsController *)fetchedResultsController { 

if (_fetchedResultsController != nil) { 
    return _fetchedResultsController; 
} 

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 
NSEntityDescription *entity = [NSEntityDescription 
           entityForName:@"Shows" inManagedObjectContext:managedObjectContext]; 
[fetchRequest setEntity:entity]; 

NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"downloadCount" ascending:NO]; 

[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]]; 

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"showId IN %@", resultsArray]; 
[fetchRequest setPredicate:predicate]; 

[fetchRequest setFetchBatchSize:20]; 

NSFetchedResultsController *theFetchedResultsController = 
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest 
            managedObjectContext:managedObjectContext 
             sectionNameKeyPath:nil 
               cacheName:nil]; 

self.fetchedResultsController = theFetchedResultsController; 
_fetchedResultsController.delegate = self; 

[sort release]; 
[fetchRequest release]; 
[theFetchedResultsController release]; 

return _fetchedResultsController;  

} 

回答

5

這將是最好使用一個謂語。例如:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 

// Set the entity for the fetch request. 
NSEntityDescription *entity = [NSEntityDescription entityForName:@"EntityName" inManagedObjectContext:managedObjectContext]; 
[fetchRequest setEntity:entity]; 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"myID IN %@", IDArray]; 

// Set the predicate for the fetch request. 
[fetchRequest setPredicate:predicate]; 

// Perform the fetch. 
NSError *error; 
NSArray *array = [managedObjectContext executeFetchRequest:fetchRequest error:&error]; 
[fetchRequest release]; 

這是一個最原始的例子,因爲我不知道你的ID或什麼是核心數據的形式,但基本上你可以搜索核心數據存儲陣列中唯一的ID並且可以進一步實現謂詞以只返回某些值。這應該至少讓你開始

+0

我所缺少的是@「myID IN%@」,IDArray但是,我仍然有一個問題,因爲fetchRequest沒有返回任何值,即使我知道IDArray有200條目。我會將我的代碼添加到問題中。 – 2011-06-05 01:20:26

+0

看着它,我不能說我看到你有什麼問題。執行實際的'performFetch:'部分的代碼怎麼樣? – justin 2011-06-05 03:00:58

+0

問題是,我正在創建resultsArray從請求到服務器的JSON字符串。該表正在加載零單元格,因此調用[self.tableView reloadData]; fetchRequest返回後仍然沒有任何作用。我可能會在用戶有機會訪問此頁面之前,在應用程序委託中發出請求並更新核心數據。 - Slev ...感謝您的幫助。 – 2011-06-05 04:02:14