数组有追加,但里面没有值
Posted
技术标签:
【中文标题】数组有追加,但里面没有值【英文标题】:Array has append, but no value inside 【发布时间】:2015-12-17 02:47:44 【问题描述】:我在我的 Swift 文件中声明了一个字符串数组。
var postTitleArray : [String] = []
在我的 viewDidLoad
方法中,我已将值附加到我的数组中...
RestApiManager.sharedInstance.makeGetRequest("/development/vw_posts?filter=parent_term_id%20%3D%20%22%5B82%5D%22", onCompletion: json in
for result in json["record"].arrayValue
let postTitle = result["post_title"].stringValue
print(postTitle)
self.postTitleArray.append(postTitle)
)
除此之外,我使用数组的计数到 numberOfRowsInSection 来设置我的 tableView 的行数...
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
return self.postTitleArray.count
但是,numberOfRowsInSection 已经返回 0,为什么会发生这种情况,我已经为我的 postTitleArray 赋值,任何人都可以帮我看看这个吗?赞赏...
【问题讨论】:
【参考方案1】:在调用 numberOfRowsInSection
之前,您的 API 调用可能尚未完成。
填充postTitleArray
后,尝试在UITableView
实例上调用reloadData
。 (我在这里假设您有一个对您的 UITableView
的引用,它被称为 tableView
)
RestApiManager.sharedInstance.makeGetRequest("/development/vw_posts?filter=parent_term_id%20%3D%20%22%5B82%5D%22", onCompletion: json in
for result in json["record"].arrayValue
let postTitle = result["post_title"].stringValue
print(postTitle)
self.postTitleArray.append(postTitle)
self.tableView.reloadData()
)
【讨论】:
我做到了伙计,百万感谢您的回答!你介意向我解释一下为什么我们应该在追加到数组之后重新加载表数据吗? 没问题。更新UITableView
数据源不会自动重新加载表。作为开发人员,您需要决定何时适合刷新表格。例如,如果您要向数组中添加 1000 个标题,则在附加单个标题后调用 reloadData
可能会非常慢。
好吧,你说的这个情况我明白了,如果我们真的得到了1000条Array里的记录,我们应该在一开始就限制获取的数量吧?
更一般地说,当数据源更改时,您可能不想更新用户界面的原因有很多。您有权在适当的时候致电reloadData
更新您的用户界面。
现在知道了,感谢您的信息。万分感谢。【参考方案2】:
你应该检查:
if let postTitle = result["post_title"]?.stringValue
self.postTitleArray.append(postTitle)
self.tableView.reloadData()
【讨论】:
以上是关于数组有追加,但里面没有值的主要内容,如果未能解决你的问题,请参考以下文章