2010-02-11 15 views

回答

5

通常使用核心數據,您將設計並使用滿足您需求的數據模型。你不應該用SQL來思考它 - 它甚至不需要使用SQL進行存儲 - 也不應該嘗試直接使用謂詞將SQL查詢轉換爲提取請求,等等。

這就是說,在構建謂詞時考慮SQL WHERE子句有時會很有幫助,但真正的提取請求歸結爲您需要獲取的實體以及如何過濾和/或排序集合等。

Fetch請求僅限於一個實體,所以我認爲您需要多個提取請求來模擬您的查詢。

您的Core Data數據模型是什麼樣的?你想達到什麼目的?你試過什麼了?

UPDATE
這聽起來像你的數據模型包括兩個實體:飲料和成分與它們之間的許多一對多的關係:

飲料< < - >>成分

注在Core Data中,除非您明確地創建它,否則不存在DrinkIngredient實體(對於多對多關係有一個額外的表格,但它是從您抽象出來的)。既然你想在附加表中的行相對應的量的價值,我會建議增加在覈心數據DrinkIngredient實體:

飲料< - >> DrinkIngredient < < - >成分

注意事項:a DrinkIngredient只有一種飲料和一種成分。飲料可以有許多DrinkIngredients和成分可以用於許多DrinkIngredients。

這聽起來像你想要得到一個特定的飲料成分列表的名稱和金額。要做到這一點,只需取DrinkIngredient對象具有過濾謂詞是這樣的:

// assuming "aDrink" is a reference to a particular Drink object 
// and "drink" is the relationship from DrinkIngredient to Drink 
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"drink == %@",aDrink]; 

// if the fetch request result array is named "ingredientList" 
// and the relationship from DrinkIngredient to Ingredient is "ingredient" 
for (DrinkIngredient *di in ingredientList) { 
    NSString *ingredientName = di.ingredient.name; 
    NSUInteger amount = di.amount.integerValue; 

    // use "ingredientName" and "amount" here 
} 

由於您使用的核心數據,而不是SQL,你做不同的事情。例如,如果您想顯示所有飲料的名稱和含量的配料列表,則只需獲取所有飲料對象(不含過濾器謂詞),並通過飲料與飲料配料的關係訪問配料。

同樣,你應該考慮你正在努力完成的任務,並恰當地設計和使用你的數據模型。你不應該考慮SQL或查詢。

+0

那麼上面的查詢是我用於我的SQLite的實際查詢,我嘗試切換到coredata。因此,我有1個飲料表,它有drinkName和drinkID,InGredient有成分名和成分ID表。 Drink_Ingredient表代表Drink和Ingredient之間的多對多關係,1種飲料可以有多種成分,1種成分可以在不同飲料的配方中。我知道如何從1個實體獲取請求,但這種情況如何?我是否需要更改我的分貝設計? – 2010-02-11 15:51:48

+0

我根據這些附加信息更新了我的答案並提供了更多建議。如果您有任何問題,請告訴我。 – gerry3 2010-02-11 18:52:19

+0

非常感謝。 – 2010-02-13 17:49:50