1

我要拉我的頭髮試圖找出爲什麼這是行不通的。搜索CoreData關係

我有兩個實體:

Quote 

Customer 

一個Quote有一個Customer一個一對一關係屬性簡稱「customer」。客戶有一個CoreData objectID(顯然)。我試圖搜索所有報價,然後根據CustomerobjectID返回具有與其關聯的特定客戶的報價。通過我設法讓這所有的教程閱讀,但我不斷收到崩潰:

+ (void)fetchQuotesForCustomerID:(NSManagedObjectID*)objectID results:(void(^)(NSError* error, NSArray *fetchedResults))completion { 

    NSManagedObjectContext *context = [[QuoteGenerator sharedGenerator] managedObjectContext]; 

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

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"customer.objectID == %@", objectID]; 

    [fetchRequest setPredicate:predicate]; 

    NSError *error; 

    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error]; 

    if (error) { 
     NSLog(@"fetch error = %@", [error localizedDescription]); 
     completion(error, nil); 
    } else { 
     NSLog(@"fetch count = %d", fetchedObjects.count); 
     completion(nil, fetchedObjects); 
    } 
} 

輸出錯誤:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath customer.objectID not found in entity <NSSQLEntity Quote id=13>'

是在斷言設置錯了嗎?通過文檔閱讀說,你可以使用點語法來訪問謂詞中的屬性。

請幫助...

+2

如果一個客戶能你爲什麼不使用一個一對多的關係,簡單地使用核心數據找到相關引用的對象有很多報價? – Gary 2013-02-26 05:41:20

+0

@加里謝謝你的幫助。帶我到正確的答案! – random 2013-02-26 05:48:33

回答

1

你不應該需要做一個獲取所有,核心數據應該生成你的客戶對象的報價員,將返回所有相關引用對象的NSSet中。

+0

你的權利!經過一整夜的休息之後,它們都在一起:)謝謝你的幫助 – random 2013-02-26 17:21:53

+0

如果沒有獲取請求,你會失去方便的fetchedResultsController,這爲您提供了處理更新和內容的巨大可能性。這就是我爲什麼要尋求解決方案的原因。 – Trantec 2016-08-24 18:13:27

3

原來睡眠不足和@Gary使我正確的答案。

  1. 我應該有一個從客戶到報價的一對多關係。

  2. 當比較的實體不必NSManagedObjectID財產明確說明它。所以對NSPredicate進行如下修改解決了我的問題。

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY customer == %@", objectID];