这是我找到的唯一触发中止的方法。如果有人以其他方式发帖,我会删除这个答案。
首先要知道的是,对于这个答案,无论你要管理的是哪个孩子
Transaction
上必须有一个
价值
事先不能
. 例如,如果尝试运行
交易
评论\u计数
邮递
0
(目前尚无评论)。
评论\u计数
永远不会更新
:
var dict = [String: Any]()
dict.updateValue(postId_123, forKey: "postId")
dict.updateValue(0, forKey: "comments_count") // *** this is important ***
dict...
let postsRef = ...child("posts").child(postId_123)
postsRef.updateChildValues(dict)
交易
在
评论\u计数
,如果值为
无
然后这个帖子被删除了(这是假设没有其他方法可以删除)
评论\u计数
无
那就跑吧
TransactionResult.abort()
. 内部
completionBlock
你去看看
error
是
无
let postsRef = Database.database().reference().child("posts").child("postId_123").child("comments_count")
postsRef.runTransactionBlock({ (mutableData: MutableData) -> TransactionResult in
// if nil then the post was deleted
let checkIfCountExists = mutableData.value as? Int
if checkIfCountExists == nil {
return TransactionResult.abort()
}
// not nil then continue on
var currentCount = mutableData.value as? Int ?? 0
mutableData.value = currentCount - 1
currentCount = mutableData.value as? Int ?? 0
if currentCount < 0 {
mutableData.value = 0
}
return TransactionResult.success(withValue: mutableData)
}, andCompletionBlock: { [weak self](error, completion, snap) in
if !completion || (error != nil) {
print("The value wasn't able to update")
print(error?.localizedDescription as Any)
if error == nil {
print("*** transaction value is nil ***")
return
}
// there is a value there but something else went wrong so try again
} else {
print("The value updated")
}
})