我是Firebase的新手。也不擅长DB。
我真的希望人们可以就我的数据库设计和检索数据代码给出建议。
我按如下方式设计了数据库。
评论有一个用于订购的createTs。但是内容不应该按创建时间排序。所以我把一个"索引"键入帖子中的内容信息。(我不确定这是不是一个好方法)
关于数据检索,我创建了一个dataManager对象来加载数据。
DataManger.swift
func loadPosts(completeBlock : ([Post]) -> Void ) {
ref.child("posts").observeEventType(.Value , withBlock: { snapshot in
var postList : [Post] = []
if snapshot.value is NSNull {
} else {
for post in snapshot.children {
let postSnap = post as! FIRDataSnapshot
let post = Post()
post.setValue(withSanpShot: postSnap)
post.commentList = []
for key in post.comments.keys {
self.loadPostComment(withKey: key, completeBlock: { (comment) in
post.commentList.append(comment)
})
}
post.contentList = []
for key in post.contents.keys {
self.loadPostContent(withKey: key, completeBlock: { (content) in
post.contentList.append(content)
})
}
postList.append(post)
}
}
completeBlock(postList)
})
}
func loadPostComment(withKey key: String, completeBlock:(Comment) -> Void) {
ref.child("post-comments").child(key).observeEventType(.Value, withBlock: { commentSnapShot in
let comment = Comment()
comment.setValue(withSanpShot: commentSnapShot)
completeBlock(comment)
})
}
func loadPostContent(withKey key: String, completeBlock:(PostContent) -> Void) {
ref.child("post-contents").child(key).observeEventType(.Value, withBlock: { contentSnapShot in
let content = PostContent()
content.setValue(withSanpShot: contentSnapShot)
completeBlock(content)
})
}
Post.swift的结构。
class Post: NSObject {
var postID : String
var authorID: String
var title: String
var createTS : NSNumber
var comments : [String : AnyObject]
var contents : [String : AnyObject]
var commentList : [Comment] {
didSet {
//TODO: add some closure to update view.Maybe also need sorting codes
print("commentList : \(commentList)")
}
}
var contentList : [PostContent] {
didSet {
//TODO: add some closure to update view.Maybe also need sorting codes
print("contentList : \(contentList)")
}
}
}
我不确定我所做的工作是使用它的正确方法。虽然我可以得到我想要的数据。
请给我建议。这对我很有帮助。感谢。