使用swift忽略FirebaseDB中的记录

时间:2018-05-07 11:33:22

标签: swift firebase firebase-realtime-database

我在一个快速的应用程序上工作,该应用程序显示从firebase到表视图控制器的记录。

我已经成功地提取了所有数据,但我已经在数据库中添加了另一个名为“secretKey”的字段..这不需要在表视图中使用,因为它在应用程序的其他地方使用

https://i.stack.imgur.com/ENAyM.png

但是现在每次我尝试运行应用程序时都会出现以下错误

2018-05-07 12:24:24.616490+0100 Loop Guardian[21847:9857567] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSTaggedPointerString 0xa030818c015ea1f9> valueForUndefinedKey:]: this class is not key value coding-compliant for the key createdAt.'
*** First throw call stack:
(0x18204b164 0x181294528 0x18204ae2c 0x1829fe434 0x182944e20 0x182944874 0x18297d930 0x1030084b0 0x103008740 0x1030f2840 0x1044892cc 0x10448928c 0x10448dea0 0x181ff3344 0x181ff0f20 0x181f10c58 0x183dbcf84 0x18b6695c4 0x10301de44 0x181a3056c)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

只有当密钥出现在数据库中时才会发生这种情况。如果我将其删除,应用程序运行正常。

我不知何故需要忽略这个字段

下面是用于从数据库中提取记录的代码

func observeMessages() {
    let key = UserDefaults.standard.value(forKey: "uid") as! String
    DBrefs.databaseMessages.child(key).observe(.value, with: { (snapshot) in
            if snapshot.exists() {
                let messageData = snapshot.value as! Dictionary<String, AnyObject>
                self.dataArr = []
                for (key,data) in messageData {
                    self.dataArr.append(data)
                }
                //THIS IS WHERE THE ERROR IS THROWN.. THREAD 1: SIGNAL SIGABRT
                self.dataArr = (self.dataArr as NSArray).sortedArray(using: [NSSortDescriptor(key: "createdAt", ascending: true)]) as [AnyObject]
                self.tblMessage.reloadData()
            }
            else {
            }
        })
}

感谢任何帮助

由于 奥利弗

1 个答案:

答案 0 :(得分:0)

for (key,data) in messageData { 
    if (key == "secreyKey") {
       continue;
    }
    self.dataArr.append(data)
}

还可以使用Swift方法对Array进行排序。请勿使用NSArray使用Array

如下面的代码:

self.dataArr.sorted(by: {$0["createdAt"] as? Int64 ?? 0 < $1["createdAt"] as? Int64 ?? 0})