Search code examples
iosswiftrealm

How to add each food to own food category in realm?


I have nested class like this:

struct Category {
    let name : String
    let foods : [Food]
}

struct Food {
    let name : String
    let price : Double
}

let categories = [
    Category(name: "Breakfast", foods : [
        Food(name: "Hafta İçi Kahvaltısı", price: 18.0),
        Food(name: "Pazar Kahvaltısı", price: 25.0),
        Food(name: "Diyet Kahvaltı", price: 22.0),
        Food(name: "Köy Kahvaltısı", price: 15.0),
        Food(name: "Ege Kahvaltısı", price: 30.0)]),
    Category(name: "Hamburger", foods : [
        Food(name: "Big TezBurger", price: 26.0),
        Food(name: "TezRoyal", price: 24.0),
        Food(name: "Double TezzBurger", price: 17.0),
        Food(name: "TezChicken", price: 21.0),
        Food(name: "Köfteburger", price: 28.0)])
]

I want above structure in Realm database.

First of all I created Category table(class) in Realm with below codes:

let realm = try! Realm()
var categoryDB = Category()
categoryDB.name = "Breakfasts"
try! realm.write {
     realm.add(categoryDB)
  }

After I created Category table, I added below codes for fill the Food table for each category

categoryDB.name = "Breakfasts"
categoryDB.foods[0].name = "Hafta İçi Kahvaltısı"
categoryDB.foods[0].price = 18.0

categoryDB.name = "Breakfasts"
categoryDB.foods[1].name = "Köy Kahvaltısı"
categoryDB.foods[1].price = 20.0

But I get an error like Terminating app due to uncaught exception 'RLMException', reason: 'Index 0 is out of bounds (must be less than 0).'

Conclusion: I need to have 5 different breakfast in Breakfast category and 5 different foods in Lunchcategory. There is no Food list data under my Category table as a foods property.

My detail realm studio screen in the link

https://youtu.be/WXnxDA15Rho


Solution

  • When you create categoryDB, its foods is empty. That is the reason why you are getting index out of bounds exception.

    You want to create Food and append it to categoryDB.foods.

    let categoryDB = CategoryDB()
    
    categoryDB.name = "Breakfasts"
    
    let food1 = Food()
    food1.name = "Hafta İçi Kahvaltısı"
    food1.price = 18.0
    
    let food2 = Food()
    food2.name = "Köy Kahvaltısı"
    food2.price = 20.0
    
    categoryDB.foods.append(objectsIn: [food1 , food2])
    
    try! realm.write {
        realm.add(categoryDB)
    }