我有一段简单的代码,我想我在其中使用了局部和全局变量。但是,我很难理解这里出了什么问题。我正在设置" var hhhh:Int = 0"首先。然后,在if语句中,我将" hhhh = appleCount [" count"]设置为! INT&#34 ;.由于appleCount [" count"]不为零并且具有一定的价值,所以hhhh得到它的' value(我尝试过uisng一个print语句,而hhhh在if语句中不是零),但是,稍后当我打印hhhh with print("(hhhh)")在if之外时,我再次得到零#39;值。它与局部变量和全局变量有关吗?顺便说一下,我试图在代码中与Parse通信。 非常感谢您的帮助
import UIKit
import Parse
class NewsPageViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad(
var hhhh:Int = 0
var tttt:Int = 0
var cccc:Int = 1
if cccc == 1 {
var query = PFQuery(className: "Count")
query.getObjectInBackgroundWithId("RhC25gVjZm", block: { (object: PFObject?, error: NSError?) -> Void in
if error != nil {
print(error)
} else if let appleCount = object {
appleCount["count"] = appleCount["count"] as! Int + 1
hhhh = appleCount["count"] as! Int
appleCount.saveInBackground()
}
})
}
print(hhhh)
}
}
答案 0 :(得分:1)
它与本地和全局变量无关。它与后台线程有关。参数标签“block”之后的括号{}中的代码将在稍后的后台线程中运行。
您的打印(hhhh)正在运行之前,该块有机会改变hhhh。将print语句移回块内,这样就可以看到正在设置的变量。
答案 1 :(得分:0)
希望这里的答案能够帮助将来的人,因为StackOverFlow的优秀人员现在正在帮助我。 和平!
var hhhh : [Int] = []
@IBOutlet weak var jPercent: UILabel!
@IBOutlet weak var yPercent: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
var query = PFQuery(className: "Count")
if cccc == 1 {
query.getObjectInBackgroundWithId("DcU9tdRdnl", block: { (object: PFObject?, error: NSError?) -> Void in
if error != nil {
print(error)
} else if let jCount = object {
jCount["count"] = jCount["count"] as! Int + 1
jCount.saveInBackground()
}
})
} else if cccc == 2 {
query.getObjectInBackgroundWithId("5Bq4HJbFa3", block: { (object: PFObject?, error: NSError?) -> Void in
if error != nil {
print(error)
} else if let yCount = object {
yCount["count"] = yCount["count"] as! Int + 1
yCount.saveInBackground()
}
})
}
//shouldn't use same query for findObjectsInBackgroundWithBlock and getObjectInBackgroundWithId otherwise you'll get a runtime error
var query2 = PFQuery(className: "Count")
query2.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if let users = objects {
for object in users {
if let user = object["count"] as? Int {
self.hhhh.append(user)
}
}
}
var gggg = 100*Float(self.hhhh[0])/(Float(self.hhhh[0]+self.hhhh[1]))
self.yPercent.text = String(format: "%.1f", gggg) + "%"
self.jPercent.text = String(format: "%.1f", 100 - gggg) + "%"
print(self.hhhh[0])
}
}