致命错误:在 Swift 中访问包含 10 个元素的数组时,数组索引超出范围
Posted
技术标签:
【中文标题】致命错误:在 Swift 中访问包含 10 个元素的数组时,数组索引超出范围【英文标题】:Fatal Error : Array index out of range when accessing an array of 10 elements in Swift 【发布时间】:2015-09-27 15:23:05 【问题描述】:我正在使用 SwiftyJson 和 Alamofire 访问 JSON。我已将我的产品名称放入一个数组中,但是当我尝试像这样访问它以获取 UITableView
时:product_name[0]
,我收到来自标题的错误(索引超出范围)。代码如下:
let total_products:Int = json["products"].count;
var i:Int = 0;
for (i=0;i<total_products;i++)
product_name.append(json["products"][i])
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel!.text = product_name[indexPath.row];
return cell
【问题讨论】:
numberOfRowsInSection
是如何实现的?在此方法中,您必须返回数据源数组中的项目数
它被硬编码为 10 :) 我认为我的 product_name 当我尝试在 tableView func 中访问它时它是空的。我所有打开 JSON 的代码都在 viewDidLoad 函数中。
大概,返回product_name.count
我已经尝试过了,我的 product_name 数组是空的。 product_name.count 等于 0。所以,我的 tableView 函数在 viewDidLoad 之前被调用。基本上,当我尝试访问 product_name[0] 时,数组是空的。但为什么呢?
数据源填充完毕后,您必须再次调用UITableView
中的reloadData()
【参考方案1】:
为避免超出范围错误,请确保UITableViewDataSource
返回的numberOfRowsInSection
是数组中的元素数。
return product_name.count
【讨论】:
我已经尝试过了,我的 product_name 数组是空的。 product_name.count 等于 0。所以,我的 tableView 函数在 viewDidLoad 之前被调用。基本上,当我尝试访问 product_name[0] 时,数组是空的。但为什么 ? P.S.:numberOfRowsInSection 被硬编码为返回 10。 在填充数据数组后添加tableView.reloadData()
即可。【参考方案2】:
我成功了!
我在for
循环中添加了self.tableView.reloadData();
,现在我的TableView
已填充。
谢谢你们!
【讨论】:
最好是在循环之后而不是在循环内部。以上是关于致命错误:在 Swift 中访问包含 10 个元素的数组时,数组索引超出范围的主要内容,如果未能解决你的问题,请参考以下文章
尝试访问 TabBar 时 IOS swift 致命错误 nil 异常