为什么视图 属性 必须分配给一个变量?

Why does the view property have to be assigned to a variable?

在下面的代码中,如果我注释掉分配给视图 属性 的变量,测试将失败。我指的是:

_=sut.view

然而,当取消注释该行代码时,测试通过。为什么有必要?

这是完整的单元测试:

import XCTest
@testable import ToDo

class ItemListViewControllerTests: XCTestCase {

    var sut:ItemListViewController!

    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        sut = storyboard.instantiateViewControllerWithIdentifier("ItemListViewController") as! ItemListViewController

        _=sut.view

    }

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }
    func test_TableViewIsNotNilAfterViewDidLoad(){
        XCTAssertNotNil(sut.tableView.dataSource)
        XCTAssertTrue(sut.tableView.dataSource is ItemListDataProvider)

    }

    func testViewDidLoad_ShouldSetTableViewDelegate(){
        XCTAssertNotNil(sut.tableView.delegate)
        XCTAssertTrue(sut.tableView.delegate is ItemListDataProvider)
    }

    func testViewDidLoad_ShouldSetDelegateAndDataSourceToSameObject(){
        XCTAssertEqual(sut.tableView.dataSource as? ItemListDataProvider, sut.tableView.delegate as? ItemListDataProvider)
    }


}

视图控制器在第一次访问 view 属性 之前不会加载它们的视图,因此将 view 分配给变量将加载它。

如果未加载视图,则 none 个插座将被连接,因此 sut.tableView 将是 nil,您的测试将失败。

控制器的 view 在您第一次访问它时延迟加载(自动调用 UIViewController.loadView 然后 UIViewController.viewDidLoad)。

If you access this property and its value is currently nil, the view controller automatically calls the loadView method and returns the resulting view.

Because accessing this property can cause the view to be loaded automatically, you can use the isViewLoaded method to determine if the view is currently in memory. Unlike this property, the isViewLoaded property does not force the loading of the view if it is not currently in memory.

(来自 UIViewController.view

加载控制器视图意味着它的所有子视图都已加载并连接到出口,因此如果您不加载视图,tableView出口将是nil

分配给 _ 只是为了消除编译器关于未使用结果的警告。在 iOS 9 及更高版本上,您可以使用 sut.loadViewIfNeeded()

实现相同的效果