2011-09-15 200 views
18

我在我的核心數據模型中定義了一個名爲「RemainingGaneProjections」的獲取請求。我想要執行該提取請求並按照實體的某個屬性對結果進行排序。我的代碼如下所示:將排序描述符應用於從模板創建的NSFetchRequest

NSFetchRequest *projectionsRequest = [model fetchRequestTemplateForName:@"RemainingGameProjections"]; 
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"confidence" ascending:NO]; 
[projectionsRequest setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]]; 

當我嘗試執行該代碼時,出現以下消息崩潰:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Can't modify a named fetch request in an immutable model.' 

我在這崩潰發生的調試確認,當我執行setSortDescriptors方法在我的NSFetchRequest上。我一直無法弄清楚爲什麼會發生這種情況。

對此處發生了什麼的任何解釋?當檢索需要排序的數據時,我應該使用另一種方法嗎?

回答

35

我在蘋果文檔中發現了所有地方的答案。由於我的提取請求沒有替換參數,因此我使用了fetchRequestTemplateForName方法而不是fetchRequestFromTemplateWithName。事實證明,核心數據編程指南這樣說:

如果模板沒有替代變量,你必須:

  1. 使用fetchRequestFromTemplateWithName:substitutionVariables:並通過 零的變量論據;
  2. 使用fetchRequestTemplateForName:和 複製結果。如果您嘗試使用由 fetchRequestTemplateForName返回的獲取請求,則會生成一個異常(「不可修改 修改不可變模型中的命名獲取請求」)。

我修改了讀取請求初始化做到這一點:

NSFetchRequest *projectionsRequest = [[model fetchRequestTemplateForName:@"RemainingGameProjections"] copy]; 

,現在一切按預期工作。

+0

我假設你還爲'projectionRequest'添加了一個相應的'release'。 –

+12

不 - 我在爲這個項目使用ARC;) –