【发布时间】:2017-02-16 17:13:55
【问题描述】:
我正在开发一个应用程序,我需要将数组中的数据从一个视图控制器发送到另一个视图控制器。我正在将一个字符串从标签中提取到一个变量中并将其附加到数组中。
var time:String = timeLabel.text!
timeArray.append(time)
print("add data")
然后我有一个prepareForSegue 函数,我想将数据从firstViewController 传递到SecondViewController
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
let nvc = segue.destinationViewController as! SecondViewController
nvc.timeArray2 = timeArray
}
在我的 secondViewController 中,我拥有 tableView 的所有必要功能,但我的 tableView 永远不会填充任何数据,因为 timeArray2 是空的,并且会导致崩溃或空的 tableView .
override func viewWillAppear(animated: Bool)
{
scrambleTimeTableView.reloadData()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return timeArray2.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = scrambleTimeTableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath)
cell.textLabel?.text = timeArray2[indexPath.row]
cell.textLabel?.font = UIFont(name: "Arial", size: 18)
cell.textLabel?.textColor = UIColor.blueColor()
print("Populate tableview")
return cell
}
我缺少什么吗?
编辑:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = scrambleTimeTableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath)
cell.textLabel?.text = timeArray2[indexPath.row]
cell.textLabel?.font = UIFont(name: "Arial", size: 18)
cell.textLabel?.textColor = UIColor.blueColor()
print("Populate tableview")
return cell
}
我在cell.textLabel?.text = timeArray2[indexPath.row] 上发生崩溃,因为 secondViewController 中的数组为空。错误显示:
线程 1:EXC_BAD_INSTRUCTION(代码=EXC_I386_INVOP,子代码=0x0)
输出显示:
空
[]
致命错误:索引超出范围
(lldb)
我让它打印数组,如果它是满/空的,以及数组是否填充到 firstViewController,看起来像这样:
添加数据
[“01.12”]
添加数据
["01.12", "01.48"]
所以我知道第一个数组正在填充,它无法向第二个控制器发送任何数据。
【问题讨论】:
-
你设置
tableView delegate和dataSource了吗? -
你在使用之前初始化数组:timeArray = [String]() 吗?
-
两者都是,我的 timeArray 已初始化,我有委托和数据源
-
尝试将 scrambleTimeTableView.reloadData() 移动到 viewDidAppeare 并添加 print(timeArray2) 以查看是否有数据。
-
它从不打印数据,所以我假设它从不加载函数,但是很难测试任何东西,因为数组仍然加载为空并导致它崩溃
标签: ios arrays swift uitableview