【发布时间】:2017-01-12 00:01:36
【问题描述】:
当我通过测试驱动的开发练习来更好地了解如何初始化和使用对象时,我遇到了一个测试用例,我在其中创建了一个对象,例如 UITableView,但我没有使用 UITableView 的 init 函数。
下面是代码示例:
import XCTest
@testable import PassionProject
class ItemListDataProviderTests: XCTestCase {
var sut: ItemListDataProvider!
var tableView: UITableView!
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
sut = ItemListDataProvider()
tableView = UITableView()
sut.itemManager = ItemManager()
tableView.dataSource = sut
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func tests_numberOfSectionsIsTwo(){
let numberOfSections = tableView.numberOfSections
XCTAssertEqual(numberOfSections, 2)
}
由于我正在学习 swift 语言和一般的 OOP,我知道初始化程序有不同的风格,我假设为了使用实例,我们需要对其进行初始化。但是在上面我能够创建一个 UITableView 实例并将它的内存存储在一个变量中。我什至被允许访问它的属性,例如 tableview.datasource。
我想知道我是否正确地认为为了使用任何类型的类的实例,它必须被初始化(如果默认情况下未设置存储的属性)?
用外行的话来说,我刚刚做了什么?我刚刚分配了内存吗?
让我感到困惑的是,在阅读 Apple 的文档时,这个类有一个我从未使用过的初始化程序,因为我从未设置框架或样式:init(frame: CGRect, style: UITableViewStyle)
提前感谢您的评论或回答。
【问题讨论】: