2013-07-03 181 views
2

創建JSON如何創建從一個核心數據實體和1 NSJSONSerialization一個JSON對象:米以下兒童?從核心數據

當試圖輸出其轉換爲JSON前的讀取請求的NSDictionary,我得到一個平坦的NSDictionary沒有設定propertiesToFetch當任何關係或我的應用程序崩潰的關係。

這是我的代碼:

NSFetchRequest *request = [NSFetchRequest 
    fetchRequestWithEntityName:@"ContrSector"]; 
request.resultType = NSDictionaryResultType; 
request.propertiesToFetch = @[@"industries"]; 
NSError *error; 
NSArray *result = [self.managedObjectContext 
    executeFetchRequest:request error:&error]; 

什麼是正確的方式做到這一點?

回答

1

propertiesToFetch預計NSPropertyDescription實例,因此嘗試更換@ 「行業」 有:

NSDictionary *attributes = [[NSEntityDescription entityForName"@ContrSector" inManagedObjectContext:self.managedObjectContext] relationshipsByName]; 
NSAttributeDescription *industriesRelationship = [attributes objectForKey:@"industries"]; 

request.propertiesToFetch = @[industriesRelationship]; 

編輯:我沒有意識到這是一個一對多的關係,從文檔:

的屬性描述可以表示屬性,一個或多個關係或表達式。屬性或 關係描述的姓名必須與 讀取請求的實體描述的名稱相匹配。

+1

它崩潰與'無效一對多的關係((),姓名等行業,isOptional 1,isTransient 0,實體ContrSector,renamingIdentifier行業...' – AlexR

+0

什麼是崩潰時,只是用「行業「 – wattson12

+0

' - [NSSQLToMany foreignEntityKey]:無法識別的選擇發送到實例0x100185460' – AlexR