Search code examples
iosswiftxcoderealm

Realm integration


I have an app that works just fine. The app is a list of cars. User can add, delete and edit cars . I tried to integrate RealmSwift to store data but got stuck. So far, data to operate the app is stored in static var in Cars class:

struct CarData {
    var name: String
    var year: String
}

class Cars {
    static var list = [
        CarData(name: "Toyota Corolla", year: "2007"),
        CarData(name: "BMW 3", year: "2011")
    ]
    static var index = -1
    static var newCar = false
}

I need realm in 2 view controllers:

  1. ListViewController - to populate tableView. Something like:
Cars.list = realmListOfCars

and the rest of the code would remain the same.
2) ConfirmViewController - to change the stored data.

if toProceed {
    if Cars.newCar {
        Cars.list.append(carToEdit!) //add new car
    } else {
        Cars.list[Cars.index] = carToEdit! //edit car
    }
} else {
    if Cars.newCar == false {
        Cars.list.remove(at: Cars.index) //delete car
    }
}
//the idea is to add something like:
realmListOfCars = Cars.list

So the idea is to simply make Cars.list equal to realmListOfCars once loaded and make realmListOfCars equal to Cars.List once a change happens.
Sounds simple but I've got completely stuck and confused creating and accessing realmListOfCars.
Begging for your help!
P.S. RealmSwift is installed


Solution

  • If you want to store data in Realm, you need to make your objects Realm objects. First, the Cars class would need to be changed

    class Cars: Object { 
    

    and then each property you want managed would need to be updated

    @objc dynamic var newCar = false 
    

    for example. You would also want to use a Realm List object as a property of the Car Data to store the cars (CarData will need to be a class, not a struct)

    let carList = List<CarData>()
    

    then, when you add a car to the Cars class carList property it will also be written to Realm as an object.

    So here's your Realm objects

    class CarData: Object {
        @objc dynamic var name = ""
        @objc dynamic var year = ""
    }
    
    class Cars: Object {
        let carList = List<CarData>()
        @objc dynamic var index = -1
        @objc dynamic var newCar = false
    }
    

    suppose your Cars object is all McLaren's and we called it allMcLarens. Here's adding a car to that list

    let myCar = CarData()
    myCar.name = "570GT"
    myCar.year = "2019"
    
    try realm.write {
        allMcLarens.carList.append(myCar)
    }
    

    A lot of this is covered in the Realm Getting Started guide as well.