Swift 子类化 UITableViewDataSource EXC_BAD_ACCESS [英] Swift Subclassing UITableViewDataSource EXC_BAD_ACCESS

查看:38
本文介绍了Swift 子类化 UITableViewDataSource EXC_BAD_ACCESS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试子类化我的 UITableViewDatasource,但是我的应用程序因 EXC_BAD_ACCESS 崩溃.没有解释没有错误消息只是崩溃.我的数据源的排序版本如下所示.

I am trying To subclass My UITableViewDatasource, However My App Crashes with EXC_BAD_ACCESS. No explanations no error messages just crashes. A Sort Version of my DataSource Looks Like This.

import UIKit

class DataSource :NSObject, UITableViewDataSource{

var tableView:UITableView
let CellIdentifier = "Cell"

init(tableView : UITableView) {
    println("Data Source")
    self.tableView = tableView
    super.init()
    self.tableView.dataSource = self
}

//:MARK UITableViewDataSource
//-----------------------------------------------------------------------------------------//
// Number Of Rows In Tableview
//-----------------------------------------------------------------------------------------//
func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int
{

    return 10
}
//-----------------------------------------------------------------------------------------//
// Cell For Row At Index Path
//-----------------------------------------------------------------------------------------//
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
    let cell = self.tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath) as UITableViewCell
    cell.textLabel.text = "Title of Row: #\(indexPath.row)"
    return cell
}  

 }

如您所见,没有什么特别的,这段代码在 Playground 中运行良好

As You can see There is nothing special, this code works fine in Playground

下面是我对 DataSource 的调用

Below is my call to DataSource

import UIKit

class ListEntriesViewController :UITableViewController{


override func viewDidLoad() {
    println("View Did Load")
    var data = DataSource(tableView: self.tableView)
    self.tableView.dataSource = data

}

}

我错过了什么,为什么此代码在 Playground 中有效,但在我的应用中无效.

What Am I missing, Why this code works works in Playground but not in my App.

谢谢

推荐答案

表视图不保留数据源.在 viewDidLoad 之后立即销毁该对象.您需要将其存储在属性中.

The datasource is not retained by the table view. The object is destroyed immediately after viewDidLoad. You need to store it in a property.

另请注意,UITableViewDataSource 是一个协议,而不是一个类.因此它不能被子类化.

Also note that UITableViewDataSource is a protocol, not a class. Hence it can't be subclassed.

这篇关于Swift 子类化 UITableViewDataSource EXC_BAD_ACCESS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆