我在 Firebase 数据库中有一个 posts 表,其结构如下:

"posts": {
         "111" : {
           "pName" : "ABC",
           "pMessage" : "Hello",
           "pOrder" : 555
         },
         "112" : {
           "pName" : "BCD",
           "pMessage" : "ELLO",
           "pOrder" : 444
         },
         "113" : {
           "pName" : "A",
           "pMessage" : "Ollo",
           "pOrder" : 555
         }.
         .....
       }

posts 表中有相当多的记录 . 所以,我已经实现了分页,从 Firebase 一次获取20条记录 . 我将 observeEventType 设置为 FIRDataEventType.Value ,以便它将监听 posts 中的所有活动 . 这是分页的代码:

/*
    retrieve current set of posts sorted by pOrder of posts
    */
   func retrievePost(offset: NSNumber, completion: (result: AnyObject?, error: NSError?)->()){
       // As this method is called from viewDidLoad and fetches 20 records at first.
       // Later when user scrolls down to bottom, its called again
       let postsRef = ref.child(kDBPostRef)
       var startingValue:AnyObject?
       // starting  value will be nil when this method is called from viewDidLoad as the offset is not set
       if offset == 0{
           startingValue = nil
       }
       else{
           startingValue = offset
       }
       // sort records by pOrder fetch offset+1 records
       self.refHandler = postsRef.queryOrderedByChild("pOrder").queryStartingAtValue(startingValue).queryLimitedToFirst(kPostLimit + 1).observeEventType(FIRDataEventType.Value, withBlock: { (snapshot) in
           // flag is for setting the last record/ 21st as offset
           var flag = 0
           var tempPost:[Post] = []
               // iterate over children and add to tempPost
               for item in snapshot.children {
                   // check for offet, the last row(21st) is offset ; Do not add last element in the main table list
                   flag += 1
                   if flag == 21 {
                       // this row is offset
                       self.kOffsetKey = item.value?["pOrder"] as! NSNumber
                       continue
                   }
                   // create Post object
                   let post = Post(snapshot: item as! FIRDataSnapshot)
                   // append to tempPost
                   tempPost.append(post)
               }
               // return to the closure
               completion(result:tempPost, error:nil)
       })
   }

每次调用此方法时,我都会设置 offset 来获取接下来的20条记录 .

现在,假设我更新了一篇文章(通过更新 pMessage ),对于该更新,引用处理程序再次调用此特定方法( retrievePost ) . 为了同步数据,我维护一个 offsetDict 字典,它将记录特定数据范围的偏移量:

offsetDict:[Range(0-20): "nil", Range(21-40):"444", Range(41-60):"666"]

因此,当更新活动调用 retrievePost 时,将从此字典中选择偏移量,否则偏移量将由正常检索活动( self.kOffsetKey )设置 . 所以我的查询是:

  • 这是实现这一特定功能的正确方法吗?

  • 现在,假设我通过后端服务向帖子添加了更多新记录,在这种情况下,我的 refHandler 如何处理获取新记录并自动显示到应用程序而没有任何 pull request 类型的东西?