繁体   English   中英

为什么必须将view属性分配给变量?

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

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

_=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分配给变量将加载它。

如果未加载视图,则不会sut.tableView插座,因此sut.tableView将为nil并且测试将失败。

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

如果访问此属性,并且其值当前为nil,则视图控制器将自动调用loadView方法并返回结果视图。

因为访问此属性可以导致视图自动加载,所以可以使用isViewLoaded方法确定视图当前是否在内存中。 与该属性不同,如果当前不在内存中,则isViewLoaded属性不会强制加载视图。

(来自UIViewController.view

加载控制器视图意味着已加载其所有子视图并将其连接到插座,因此,如果您不加载视图,则tableView插座将为nil

分配给_仅会使沉默编译器有关未使用结果的警告。 在iOS 9及更高版本上,您可以使用sut.loadViewIfNeeded()实现相同的功能

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM