【问题标题】:Why can I not assign dataSource directly?为什么我不能直接分配数据源?
【发布时间】:2023-03-25 05:09:01
【问题描述】:

我想了解为什么遵循 Swift 代码不起作用,但使用注释版本却可以。我不确定 dataSources 是否通常被包装到一个单独的类中,但我认为这并不重要。我使用的是 Xcode 6.3.2,都是最新的。

// MainViewController.swift
import UIKit
class MainViewController: UIViewController {
    @IBOutlet weak var tableView: UITableView!

    var dataSource:UITableViewDataSource?

    override func viewDidLoad() {
        super.viewDidLoad()

        // dataSource = MainTableViewDataSource()
        // tableView.dataSource = dataSource

        tableView.dataSource = MainTableViewDataSource()
    }
}

MainTableViewDataSource 只是一个实现 UITableViewDataSource 协议并使用一些虚拟数据的类。

// MainTableViewDataSource.swift
import UIKit

class MainTableViewDataSource : NSObject, UITableViewDataSource {
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 100
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1000
    }

    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return String(section + 1)
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = UITableViewCell()
        cell.textLabel?.text = "Joejoe"

        return cell
    }
}

【问题讨论】:

  • “不起作用”在什么意义上?编译器错误,运行时错误,错误结果,... ?
  • 对不起,它会引发运行时错误。但是不要在控制台中获得很多信息:'(lldb)'

标签: swift uitableview datasource


【解决方案1】:

根据苹果的文档https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableView_Class/#//apple_ref/occ/instp/UITableView/dataSource

UITableView 的

dataSource 属性在 Swift 中是 unowned ,对于 Objective-C 来说是 (assign) 意味着这个属性不会增加引用数数。所以在 viewDidLoad 函数之后,当你的 MainTableViewDataSource 的引用计数变为零时,它就会被释放。

推荐阅读:https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html

如果你没有正确地进行内存管理,你会遇到奇怪的结果——有时甚至是不一致的。

【讨论】:

  • 谢谢你。我不熟悉无主的概念。现在真的很有意义,谢谢!
猜你喜欢
  • 2012-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-25
  • 1970-01-01
  • 2021-06-02
  • 1970-01-01
  • 2012-01-08
相关资源
最近更新 更多