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.
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:
This approach will lead you to cleaner code and some other architectures(if you need)