我正在使用Alamofire來解析JSON數據。在下面提到的代碼中,除了'var id:JSON?'之外,一切工作都正常。雖然它的更新很好,但它在某個點(底部)保持返回零。我需要把這個變量放在過濾器關閉中。變量不斷返回零 - Swift iOS
class GreetingObjectHandler {
var greetings: [Greeting] = []
var id: JSON? //this variable
init(filename: String) {
Alamofire.request(.GET, "http://localhost:2403/users/me")
.responseJSON { (req, res, data, error) in
if(error != nil) {
NSLog("Error: \(error)")
}
else {
var parse = JSON(data!)
self.id = parse["id"] //updating
println(self.id) //it's fine here
}
}
let filePath = NSURL(string: "http://localhost:2403/users")
let jsonData = NSData(contentsOfURL:filePath!)
let json = JSON(data: jsonData!, options: NSJSONReadingOptions.AllowFragments, error: nil)
for (key: String, subJson: JSON) in json {
var language:String?, link: String?, description:String?, greetingText: String?
for (key1, value:JSON) in subJson {
switch key1 {
case "displayName": language = value.string
case "id": link = value.string
case "username": description = value.string
case "mainSkill": greetingText = value.string
default: break
}
}
let greeting = Greeting(language: language, link: link, description: description, greetingText: greetingText)
self.greetings.append(greeting)
self.greetings = self.greetings.filter { $0.link != "\(self.id)"} //this filter
println(self.id) //returns nil
}
}
func getGreetingsAsAnyObjects() -> [String: [AnyObject]]{
return [Constant.GreetingOBJHandlerSectionKey: greetings.map { $0 as AnyObject }]
}
}
request()是一個異步操作。你不能知道哪一行首先被調用,而不會像println(「1 \(self.if)」)那樣添加一些東西給它們。 –
它返回nil,因爲它在主線程上運行並且請求操作還沒有成功完成,值的id屬性。 –