gpt4 book ai didi

swift - 在使用 SwiftyJSON 和 Alamofire 从 API 返回数据之前渲染 UITableView

转载 作者:搜寻专家 更新时间:2023-10-31 08:34:03 27 4
gpt4 key购买 nike

当我在 viewDidLoad() 中调用 callapi() 函数时,callapi 中的 println() 会打印其中包含 Post 对象的 posts 数组,但是 viewDidLoad() 函数中的 println() 会打印一个空数组。此外,当我构建项目时,我收到此错误“ fatal error :数组索引超出范围”。 tableView 函数中的 println() 语句也打印一个空数组。表格似乎在来自 API 的数据到达之前就已呈现,我该如何解决这个问题?

var posts = [Post]()

override func viewDidLoad() {
super.viewDidLoad()
callapi()
println(self.posts)
}

func callapi(){
request(.GET, "url")
.responseJSON { (request, response, data, error) in
let json = JSON(data!)
if let jsonArray = json.array {
for post in jsonArray {
var onepost = Post(id:post["id"].stringValue,

title:post["title"].stringValue,
author:post["author"].stringValue,
post:post["post"].stringValue,
created_on:post["created_on"].stringValue,
updated_on:post["updated_on"].stringValue)
self.posts.append(onepost)
println(self.posts)
self.tableView.reloadData()
}
}
}
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath
indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "Cell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier,
forIndexPath: indexPath) as! CustomTableViewCell

println(self.posts)
let post = self.posts[indexPath.row]
// Configure the cell...
cell.titleLabel!.text = self.posts[indexPath.row].title
cell.postLabel.text = post.post
println(self.posts)
return cell
}

最佳答案

viewDidLoad 被调用时,它启动异步 callapi,但是当 viewDidLoad 完成时,posts还是空的。但是 TableView 仍将继续其初始加载过程,即使 posts 尚未填充,因此您必须确保 tableView:numberOfRowsInSection: 在以下位置返回零这点。

稍后,callapi 完成 Alamofire GET 请求并调用 reloadData。只有此时 tableView:numberOfRowsInSection: 才应该返回非零值。

最重要的是,确保 tableView:numberOfRowsInSection: 返回 posts 中的实际条目数,问题应该得到解决。

关于swift - 在使用 SwiftyJSON 和 Alamofire 从 API 返回数据之前渲染 UITableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29728221/

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