Search code examples
swiftcore-datansmanagedobject

Fetch all relationship data - Core Data


I am new to core data. I am fetching data from API and then saving them to core data.This is my dataModel.

enter image description here

Here is my API Structure,

{
"name" : "name here",
"content" :[
{
    "homeContentItems" : [
    {
         "some objects" : "values",
         "contentItemDetails": [
          {
          }, 
          {
          }
         ]
    },
    {
         "some objects" : "values",
         "contentItemDetails": [
          {
          }, 
          {
          }
         ]
    }

  ]
},
{
    "homeContentItems" : [
    {
         "some objects" : "values",
         "contentItemDetails": [
          {
          }, 
          {
          }
         ]
    },
    {
         "some objects" : "values",
         "contentItemDetails": [
          {
          }, 
          {
          }
         ]
    }

  ]
}

]
}

How can I fetch data from the Entity so I can get all data from related entity too?

I Have never worked with database before so its bit complected for me. Any help will be much appreciated.

let informedDataFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Informed360Entity")
    informedDataFetch.fetchLimit = 1
    informedDataFetch.predicate = NSPredicate()
    let tableviewData = try! context.fetch(informedDataFetch)

    let tdata : Informed360Entity = tableviewData.first as! Informed360Entity
    var contentData = tdata.toContent?.allObjects as? [ContentEntity]

I tried this code and getting data from ContentEntity table. How can I get other 2 tables data too so I can use to display in tableview.


Solution

  • You do it the same way as you did with ContentEntity but now you use the two properties that represent the relationships, contentDetailItem and homeContentItems, which both will return a Set.

     for content in contentData {
         let contentDetailItems = content.contentDetailItem
         let homeContents = content.homeContentItems
         //...
     }