我想异步更新一个方法的一些初始值,但是我找不到一种方法来尊重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)
})
}
}
答案 0 :(得分:0)
在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)
}