Search code examples
swiftmodel-view-controllerdesign-patternsrealm

What does a swift model class look like if I follow MVC and persist data by RealmSwift?


I am new to Swift and I'm developing a To-do app just for practicing. In this app, the data is persisted using RealmSwift and I tried to follow the MVC design pattern. However, I got an advice that the class model is lack of logic and need to be adjusted. Please give me some advices to improve my code. In my main Viewcontroller, I created these variables to persist data

let realm = try! Realm()

var itemList : Results<Item>!

and there are some method also in my main View Controller to manipulate data:

func save(item : Item) {
        do {
            try realm.write {
                realm.add(item)
            }
        }

        catch{
            print("Error saving category, \(error)")
        }

        tableView.reloadData()
    }

    func loadItems() {

        itemList = realm.objects(Item.self)

        tableView.reloadData()

    }

Here is my data model:

import Foundation
import RealmSwift

class Item : Object {
    @objc dynamic var title : String = ""
    @objc dynamic var done : Bool = false
    @objc dynamic var note: String = ""
    @objc dynamic var dateCreated : Date?

    convenience init(title: String, note: String) {
        self.init()
        self.title = title
        self.note = note
        self.dateCreated = Date()
        self.done = false
        }


}

For my understanding, the Model in MVC should contain the data class and all the method to manipulate the data, but I don't know how to restructure my code. Here is full of my code https://github.com/lequocgiom/Reminder/tree/master/Reminder2

Thanks for your time, I will be very appreciated if someone can help me.


Solution

  • This is a very interesting question

    Basically Model should contain only properties so it works only as "storage"

    Methods to manipulate models should be placed in "Controller" part of your code

    But please do not put it in ViewController as some tutorials do. It is very bad practice and should be avoided to keep your architecture clean(if MVC can be clean(Just a joke)). Create a new class like ItemManager which will deal with models.

    So your Logic will look like this:

    1. "Controller"(Busines logic) calls ItemManager when he wants to get/delete/edit/create new models
    2. ItemManager performs a query(or other things) with Realm(CoreData/SQL/REST/...) and returns items back to "Controller"

    This approach will lead you to cleaner code and some other architectures(if you need)