【发布时间】:2019-10-22 04:46:34
【问题描述】:
我正在尝试使用这两个库从 json(Link:"https://learnappmaking.com/ex/books.json") 将“作者”数据保存到名为“作者”的全局变量中。但它只适用于func Alamofire.request(url).responseJSON 的尾随关闭。当我从尾随闭包之外的某个地方访问名为“authors”的全局变量时,我得到的是一个空的字符串数组。
有人能解释一下这种奇怪情况背后的原因吗? 非常感谢。
class ViewController: UIViewController {
var authors = [String]()
let url = "https://learnappmaking.com/ex/books.json"
func getAuthorsCount() {
print("the number of authors : \(authors.count)") // I hope that here, the number of authors should be 3 too! actually, it is 0. Why?
// this for loop doesn't get excuted
for author in authors {
print(author)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
Alamofire.request(url).responseJSON { response in
if let data = response.data {
if let json = try? JSON(data: data) {
for item in json["books"].arrayValue {
var outputString: String
print(item["author"])
outputString = item["author"].stringValue
//urlOfProjectAsset.append(outputString)
self.authors.append(outputString)
print("authors.count: \(self.authors.count)")
}
}
}
}
getAuthorsCount()
print("-------------")
}
}
实际输出为:
更新: 我调整了我的代码:
class ViewController: UIViewController {
var authors = [String]()
let url = "https://learnappmaking.com/ex/books.json"
func getAuthorsCount() {
print("the number of authors : \(authors.count)")
// this for loop doesn't get excuted
for author in authors {
print(author)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
Alamofire.request(url).responseJSON { response in
if let data = response.data {
if let json = try? JSON(data: data) {
for item in json["books"].arrayValue {
var outputString: String
//print(item["author"])
outputString = item["author"].stringValue
//urlOfProjectAsset.append(outputString)
self.authors.append(outputString)
//print("authors.count: \(self.authors.count)")
}
self.getAuthorsCount() // I added this line of code.
}
}
}
getAuthorsCount()
print("-------------")
}
}
但是为什么func getAuthorsCount()(不是self.version)仍然打印一个空的字符串数组?我认为结果应该与结果相同
func self.getAuthorsCount() 已打印。
我现在很迷茫...
同样,我想使用保存在名为“authors”的变量中的数据,但我只得到一个空字符串数组。
【问题讨论】:
-
确保在获得结果后访问 getAuthorsCount。从您的示例中不清楚
-
您在请求从服务器返回之前调用了
getAuthorsCount()。将它移到回调中,在for语句之后,它将起作用。 -
@Lirik 嗨,我是 swift 的 iOS 开发新手。您能否给我一些提示,告诉我如何确保在获得代码结果后访问 getAuthorsCount()?
-
@SunsetWan 现在工作了吗?
-
@SunsetWan 您添加的行正是答案。其他 getAuthorsCount() 和 print() 语句不相关。
标签: ios json swift alamofire swifty-json