每次我运行 runTransactionBlock
时,它都会给我 null ,虽然该位置有一个节点: -
FIRMutableData(最顶层的交易)(null)
在该行: - print(totalPost)
func updateTotalNoOfPost(){
let prntRef = FIRDatabase.database().reference().child("TotalPosts")
prntRef.observeSingleEventOfType(.Value, withBlock: {(totalSnap) in
if totalSnap.exists(){
prntRef.child("noOfTotalPost").runTransactionBlock({ (totalPost: FIRMutableData) -> FIRTransactionResult in
print(FIRAuth.auth()!.currentUser!.uid)//Giving me correct userID
print(totalPost)//<Null>
print(prntRef.child("noOfTotalPost"))//Giving me correct path to that node
totalPost.value = totalPost.value as! Int + 1
return FIRTransactionResult.successWithValue(totalPost)
}, andCompletionBlock: { (err, TF, snap) in
print(err?.localizedDescription)
print(TF)
print(snap!.value)
FIRTransactionResult.abort()// Am i using this right?
})
}else{
prntRef.setValue(["noOfTotalPost": 1])
}
})
}
我的JSON树结构是这样的: -
{
"TotalPosts" : {
"noOfTotalPost" : 1
},
"Users" : {
"FBLXPOxBomakPCQuDTilGC7Becu2" : {...},
"1DASWPOxBomakPCdasd1d123au6" : {...},...}}
我正在为我的数据库使用默认安全规则: -
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
我想要的是每次用户创建帖子时都会增加noOfTotalPost
子节点的值: -
我已经使用observeSingleEventOfType.
:
let prntRef = FIRDatabase.database().reference().child("TotalPosts")
prntRef.child("noOfTotalPost").observeSingleEventOfType(.Value, withBlock: {(totalSnap) in
if totalSnap.exists(){
if let tNo = totalSnap.value as? Int{
prntRef.child("noOfTotalPost").setValue(tNo+1)//Working Fine
}
})
}else{
prntRef.setValue(["noOfTotalPost": 1])
}
})
但是无法弄清楚为什么runTransactionBlock
无法工作!
答案 0 :(得分:1)
正如@Frank在评论中所说, runTransactionBloack
的行为最初会返回NSNull
,但如果该位置已有值,则会再次触发。如果更新值时发生冲突,它将再次触发。
代码: -
func updateTotalNoOfPost(completionBlock : (() -> Void)){
let prntRef = FIRDatabase.database().reference().child("TotalPosts")
prntRef.child("noOfTotalPost").runTransactionBlock({ (noOfPosts) -> FIRTransactionResult in
if let totalPost = noOfPosts.value as? Int{
noOfPosts.value = totalPost + 1
return FIRTransactionResult.successWithValue(noOfPosts)
}else{
return FIRTransactionResult.successWithValue(noOfPosts)
}
}, andCompletionBlock: {(error,completion,snap) in
print(error?.localizedDescription)
print(completion)
print(snap)
if !completion {
print("The value wasn't able to Update")
}else{
completionBlock()
}
})
}
对于基本概念: -