【发布时间】:2020-10-24 20:10:07
【问题描述】:
如果我想从数据库中检索一些数据,我可以使用snapshot.exists() 来检查它是否存在:
ref.observeSingleEvent(of: .value, with: { (snapshot) in
if !snapshot.exists() { return }
}
但是在运行Transaction 时,我只是更新了一些不再存在的东西,而不是出现错误,它更新了我没想到的 ref。
1- Transaction 应该更新的子引用:
@posts
@postId_123 // this post has actually been deleted
-url: ...
-timeStamp: ...
-comments_count: 10
-2 用户可以在不实际查看的情况下删除其中一个 cmets。一旦发生这种情况,cmets_count 就会减少。
let postsRef = Database.database().reference().child("posts").child("postId_123").child("comments_count")
postsRef.runTransactionBlock({ (mutableData: MutableData) -> TransactionResult in
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)
} else {
print("The value updated")
}
})
3- 问题是如果 postId_123 在 Transaction 运行之前被删除,上述 Transaction 会导致 postId_123 被放回帖子引用中:
@posts
@postId_123 // this postId has been been put back but should no longer exist
-comments_count: 0
如果 mutableData 的子级不再存在,我该如何运行 TransactionResult.abort()?
let postsRef = Database.database().reference().child("posts").child("postId_123").child("comments_count")
postsRef.runTransactionBlock({ (mutableData: MutableData) -> TransactionResult in
if !mutableData.exists() { // *** this check isn't real and is used just as an example ***
return TransactionResult.abort() // this is real
}
var currentCount = mutableData.value as? Int ?? 0
// ...
})
【问题讨论】:
标签: ios swift firebase firebase-realtime-database