簡體   English   中英

方法如何被調用兩次?

[英]How does a method get called twice?

我正在學習Swift,並且在課堂上有以下方法:

 override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // Return the number of rows in the section.
    return countries.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as UITableViewCell
    cell.textLabel!.text =  countries[indexPath.row]
    return cell
}

這讓我感到困惑,因為我在可以調用兩次的方法(即tableView)之前還沒有編程。 這怎么可能?

您不應認為該方法僅由括號前的名稱定義。 如果參數不同,則它是完全不同的方法。

這些不是方法調用。 這些是函數定義。 但是,由於它們共享相同的函數名稱,因此如果不指定參數名稱就無法調用它們。 調用它們的方式是這樣的(盡管它是在UITableView內部完成的,因此在這種特殊情況下您不必擔心):

tableView(theTableView, numberOfRowsInSection:theSection);
tableView(theTableView, cellForRowAtIndexPath:theIndexPath);

請注意, sectionindexPath分別是函數內部使用的外部參數名稱numberOfRowsInSectioncellForRowAtIndexPath名稱。

有關函數名稱,參數和簽名的一般結構的更多信息,請參見此處的Swift文檔: https : //developer.apple.com/library/ios/documentation/swift/conceptual/swift_programming_language/Declarations.html#/ / apple_ref / DOC / UID / TP40014097-CH34-XID_598

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM