2014-03-12 23 views
0

enter image description here選擇一個在覈心數據一對多的關係取指不工作

我用這個代碼來選擇與特定類別的所有產品,但它不工作,,什麼是正確的斷言,我可以用於獲得所有與此類別相關的產品

注意: 我從服務器上單獨獲取類別列表並插入它們,然後從服務器獲取產品列表並插入它們,但是現在我發現該產品並沒有不知道他的類別,我使用restkit庫來解析並插入到數據庫中,所以我如何告訴產品該類別,restkit自動完成所有工作

如何將產品列表設置爲我從服務器獲得的類別?

//--fetching inserted Results from core data 
    // Getting products 
    NSError *error; 
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"productId" ascending:YES]; 
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor , nil]; 
    [fetchRequest setSortDescriptors:sortDescriptors]; 
// NSPredicate *predicate = [NSPredicate predicateWithFormat:@"category = %@ ",tempCategoryHolder]; 
// [fetchRequest setPredicate:predicate] ; 


    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Product" 
               inManagedObjectContext:self.managedObjectContext]; 
    [fetchRequest setEntity:entity]; 

    fetchedObjectsProducts = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error]; 
+0

謂詞爲什麼被註釋掉?它是如何工作的?什麼是'tempCategoryHolder'?如果你登錄'tempCategoryHolder.products',你會得到什麼? – Wain

+0

不,我只是評論它,因爲代碼不能很好地工作 – mohamed

+0

顯示你的映射。你需要做一個外鍵映射連接... – Wain

回答

0

我會做這樣的假設tempCategoryHolder持有的categoryId:

NSError *error = nil; 
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Product"]; 
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"category.categoryId = %@", tempCategoryHolder]; 
fetchRequest.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"productId" ascending:YES]]; 
NSArray *fetchedObjectsProducts = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error]; 

否則更新謂詞指類別對象,或者不同的類別屬性。

+0

我從服務器單獨獲取分類列表並插入它們,然後從服務器獲取產品列表並插入它們,但是現在我發現產品不知道他的類別,我使用restkit庫來解析和插入數據庫,,所以我怎麼能告訴產品,類別,restkit自動完成所有工作 – mohamed

+0

如何設置到產品列表我從服務器的類別? – mohamed

+0

我不使用RestKit,因此我不知道它如何將提取的數據存儲到Core Data中。通常你會得到JSON或XML,解析數組或目錄,一旦你持有對象,你只需插入NewObjectForEntityForName並設置它的屬性。他們的關鍵是在Product上設置Category對象以及其他Product屬性。粘貼存儲和保存代碼以供審閱。 –