I use Realm in several small projects, and I really like it. I hope to switch to its use in large projects, and I am looking for the best structure for my level of data access.
I came across this similar question and tried to collect the information I found there. The approach discussed there is a DAO pattern, so I took a picture.
This is my model class.
class Chat: Object { dynamic var id: String = "" dynamic var createdAt: Date = Date() dynamic var creatorId: String = "" dynamic var title: String? let chatMessages = List<ChatMessage>() override static func primaryKey() -> String? { return "id" } convenience init(fromJSON json: JSON) { self.init()
Then I created a ChatDAOProtocol to store all the convenient helper methods.
protocol ChatDAOProtocol { func addMessage(_ message: ChatMessage) func getChatThumbnail() -> UIImage func getParticipants(includingMe: Bool) -> [Participant]? static func getChat(fromId id: String) -> Chat? static func getChat(fromCreatorId id: String) -> Chat? }
Finally, I created another class called ChatHelper that implemented all of these protocol methods.
class ChatHelper: ChatDAOProtocol { func addMessage(_ message: ChatMessage) { } func getChatThumbnail() -> UIImage { return UIImage() } func getParticipants(includingMe: Bool) -> [Participant]? { return nil } static func getChat(fromId id: String) -> Chat? { return nil } static func getChat(fromCreatorId id: String) -> Chat? { return nil } }
This already seems to be better than sprinkling all the database-related code throughout VC and the like. But I still have some doubts.
For example, let's say if I need to get all the chat participants, now I need to call the method in the ChatHelper class. And if I want to get just the chat name, I call the title property of the Chat object itself. Not like a very unified interface. Should I include getters and setters for all properties in the helper. Thus, a Chat object is never called directly (other than instantiation).
or
Should I make the Chat object itself conform to the ChatDAOProtocol protocol? So, are all the convenient methods, as well as properties, directly accessible from the Chat object?
Or is there a better way than both of these?