gpt4 book ai didi

ios - 在 firebase 函数中拥有自己的完成处理程序(自定义类方法)

转载 作者:行者123 更新时间:2023-11-28 08:41:48 25 4
gpt4 key购买 nike

我想异步更新方法的一些初始值,但我找不到尊重 firebase 完成的方法,所以我想自己做一个,但没有运气,知道吗? (在下面的代码中,我试图更新 comlike 的值)

class POSTDATA {

var comcount : String
var comlike : Int
var post : getitems

init(comcount:String, comlike:Int, post:getitems) {

self.post = post
self.comlike = comlike
self.comcount = comcount
findComCount(){success in}
}

func findComCount(completionHandler: (Bool) -> ()) {

let refComCount = Firebase (url: ("https://XXXXXX/COMCOUNTS/" + self.post.postid + "/comcount"))
refComCount.observeEventType(.Value, withBlock: { snap in
if snap.value is NSNull {
self.comcount = "0"

} else {
if snap.value == nil {
self.comcount = "0"
} else {
self.comcount = String( snap.value!)
}
}

completionHandler(true)
})

}

最佳答案

在 init 调用中执行异步操作很奇怪,相反你可以使用动态变量和 KVO 观察之类的东西:

class POSTDATA:NSObject { //Inherit your class from NSObject to allow KVO observing

var comcount : String
var comlike : Int
var post : getitems

dynamic var completed:Bool = false //Here you declare your dynamic var


init(comcount:String, comlike:Int, post:getitems) {

self.post = post
self.comlike = comlike
self.comcount = comcount
findComCount();
}

func findComCount() {

let refComCount = Firebase (url: ("https://XXXXXX/COMCOUNTS/" + self.post.postid + "/comcount"))
refComCount.observeEventType(.Value, withBlock: { snap in
if snap.value is NSNull {
self.comcount = "0"

} else {
if snap.value == nil {
self.comcount = "0"
} else {
self.comcount = String( snap.value!)
}
}

self.completed = true //Assign to it value 'true' when update i completed
})

}
}

然后在您的 viewController 中执行如下操作:

var postDataObject:POSTDATA = POSTDATA("String",0,getitemObj);

override viewDidLoad() {
super.viewDidLoad()
postDataObject.addObserver(self, forKeyPath: "completed", options: NSKeyValueObservingOption, context: nil)
}

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if (keyPath != nil){
if(keyPath!=="completed"){
//HERE YOU KNOW YOUR OBJECT HAS BEEN UPDATED
}
}
}

deinit {
postDataObject.removeObserver(self, forKeyPath: "completed", context: nil)
}

关于ios - 在 firebase 函数中拥有自己的完成处理程序(自定义类方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36343415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com