我一直在一些小项目中使用 Realm,我非常喜欢它。我希望继续在更大的项目中使用它,并且我正在寻找更好的数据访问层结构。
我遇到过这个类似的question https://stackoverflow.com/q/33592572/1077789并尝试以我在那里找到的信息为基础。那里讨论的方法是 DAO 模式,所以我尝试了一下。
这是我的模型课。
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()
// ...
}
}
然后我创建了一个ChatDAOProtocol
保存所有方便的辅助方法。
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?
}
最后我创建了另一个类ChatHelper
实现了所有这些协议方法。
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
}
}
这似乎已经比将所有与数据库相关的代码散布在 VC 和其他东西上要好。但我还是有一些疑问。
例如,假设我需要获取聊天的所有参与者,现在我必须调用ChatHelper
班级。如果我只想获取聊天标题,我可以调用title
的财产Chat
对象本身。看起来不是一个非常统一的界面。我是否应该在助手中包含所有属性的 getter 和 setter?所以Chat
对象永远不会被直接调用(除了创建一个实例)。
Or
我应该做Chat
对象本身符合ChatDAOProtocol
协议?因此,所有便捷方法以及属性都可以直接从Chat
直接对象?
或者有比这两种更好的方法吗?