在Swift UITableViewController初始化程序中传递数据

时间:2014-11-26 06:22:40

标签: ios uitableview swift

我面临一个奇怪的问题。我有一个自定义类FormDataSource,如下所示

class FormDataSource{

var Sections: Array<SectionDataProvider>?;
var Rows:Array<Array<RowDataProvider>>!;
var formData: Dictionary<String, Any?>!;

init(sections:Array<SectionDataProvider>?, withRows:Array<Array<RowDataProvider>>){
    self.Sections = sections;
    self.formData = [String:Any?]();
    self.Rows = withRows;

    for rowArray in self.Rows
    {
        for row in rowArray
        {
            self.formData.updateValue(row.actualData, forKey: row.keyForRowData);
        }
    }
}
}

UITableViewController子类FormViewController如下所示

class FormViewController:UITableViewController{

var formDataSource:FormDataSource!;

init(with  DataSource :FormDataSource) {

    self.formDataSource = DataSource;

    println("count: \(self.formDataSource.Rows.count)"); //prints 3 correctly
    super.init(style: UITableViewStyle.Plain);
}

override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {

    super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil);
}

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder);
}

override func viewDidLoad() {
    super.viewDidLoad();

    println("count: \(self.formDataSource.Rows.count)"); //crash at this line

}
}

当我创建FormViewController的新实例时,它会在viewDidLoad内崩溃

"fatal error: unexpectedly found nil while unwrapping an Optional value"

代码如下:

var dataSource = FormDataSource(sections: nil, withRows:rows);

    let joinView:FormViewController = FormViewController(with: dataSource);
    self.navigationController?.pushViewController(joinView, animated: true);

我猜原因可能是我传递的变量正在被破坏。谁能告诉我我做错了什么?

1 个答案:

答案 0 :(得分:0)

如果使用InterfaceBuilder构建TableViewController,则

init(coder)

init(nibName)
调用

进行初始化。 这意味着您的formData属性未被初始化并导致该错误。

在各种init函数中设置断点,以查看哪一个被调用。