mardi 7 mai 2019

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.

Aucun commentaire:

Enregistrer un commentaire