【发布时间】:2014-08-01 08:07:16
【问题描述】:
我遇到了一个奇怪的问题。我正在尝试以编程方式将数据源分配给表。
我使用 Interface Builder 在我的 ViewController 中为它创建了一个 UITableView 和一个 IBOutlet。我创建了一个实现UITableViewDataSource 的类。我将表的dataSource 设置为dataSource 的一个实例。一切都编译并运行良好,直到设置数据源的行在运行时执行。
错误为Thread 1: EXC_BAD_ACCESS (code=EXC_i386_GPFLT),class AppDelegate 定义行高亮显示。
class ViewController: UIViewController {
@IBOutlet weak var table: UITableView!
override func viewDidLoad() {
let ds = MyData()
table.dataSource = ds // <---- Runtime error
table.reloadData()
super.viewDidLoad()
}
// ... other methods
}
class MyData: NSObject, UITableViewDataSource {
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let cell = UITableViewCell()
cell.textLabel.text = "a row"
return cell
}
}
知道为什么我会收到此运行时错误吗?我正在将 XCode 6 beta 4 与 Swift 一起使用。
【问题讨论】:
-
你遇到了什么错误?
-
dataSource委托通常是一个weak属性,并且您不会使用范围之外的强指针保持您的ds活动,因此当@987654330 时会立即释放@ 超出了自己的范围...这可能会导致您的问题。 -
@holex 我的想法完全一样。解决方法是移行:let ds = MyData() out of the viewDidLoad, IBOutlet weak var table:UItableView
-
@Greg 我添加了错误消息。
-
感谢@holex 和@Greg。是的,这就是原因。那么,说我们通过引用而不是值设置
table.dataSource是否有意义?如果它是按值设置的,代码会起作用吗?
标签: ios xcode uitableview swift