且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从Objective-C到Swift,你必须会的(三)init的顺序

更新时间:2022-08-29 20:58:20

Objective-C的构造函数吧,就最后return一个self。里头你要初始化了什么都可以。在Swift的init函数里把super.init放在前面,然后再初始化你代码里的东西就会报错了。

所以:

1
2
3
4
5
6
7
init(frame: NSRect) {
    super.init(frame: frame)
    subviewGroup = GridViewGroup(rows: 9, columns: 9, gridView: self)
}
 
/***  Properties  ***/
let subviewGroup: GridViewGroup

 是不对的。

应该是什么样的呢:

1
2
3
4
init(frame: NSRect) {
        subviewGroup = GridViewGroup(rows: 9, columns: 9, gridView: self)
        super.init(frame: frame)
}

 具体到UITableView的时候:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        self.tableView = UITableView(frame: CGRectMake(00, CGRectGetWidth(rect), CGRectGetHeight(rect)), style: UITableViewStyle.Plain)
         
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        dlog()
        self.view.addSubview(self.tableView)
 
        self.tableView.delegate = self
 
        self.tableView.dataSource = self
 
        self.tableView.allowsSelection = true
 
    }

 在super.init之后才能用self给delegate、datasource什么的去赋值。

 

欢迎加群互相学习,共同进步。QQ群:iOS: 58099570 | Android: 330987132 | Go:217696290 | Python:336880185 | 做人要厚道,转载请注明出处!http://www.cnblogs.com/sunshine-anycall/p/4036932.html