gpt4 book ai didi

ios - 如何防止访问其他类的委托(delegate)方法?

转载 作者:行者123 更新时间:2023-11-28 10:45:17 24 4
gpt4 key购买 nike

为了制作“更多 encapsulated”应用程序,我试图为我的 View Controller 属性/方法指定访问级别。但问题是当尝试私有(private)数据源/委托(delegate)方法时,我收到一个编译时错误提示它。

例如,我有两个 View Controller :ViewControllerAViewControllerB,第一个实现了 TableView 数据源方法和 privateWork()私有(private)方法,如下:

class ViewControllerA: UIViewController, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 101
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell")!
return cell
}

private func privateWork() {
print(#function)
}
}

第二个 View Controller 有一个 ViewControllerA 的实例 - 在一个名为 setupViewControllerA() 的方法中 - 如下所示:

class ViewControllerB: UIViewController {
func setupViewControllerA() {
// in real case, you should get it from its stroyborad,
// this is only for the purpose of demonstrating the issue...
let vcA = ViewControllerA()

vcA.privateWork()
}
}

在执行 vcA.privateWork() 时会出现编译时错误:

'privateWork' is inaccessible due to 'private' protection level

太合适了!我想阻止其他类访问 vcA.privateWork()

我的问题是:简单地说,我想对数据源方法执行相同的操作,所以如果我尝试实现:

private func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 101
}

我收到一个编译时错误:

Method 'tableView(_:numberOfRowsInSection:)' must be as accessible as its enclosing type because it matches a requirement in protocol 'UITableViewDataSource'

有一个修复建议让 private 成为 internal。它导致以下代码(在第二个 View Controller 中):

vcA.tableView(..., numberOfRowsInSection: ...)

要有效,这是不合适的,没有必要让这样的数据源方法可以从其类的外部访问。

遇到这种情况怎么办?

最佳答案

您无需担心委托(delegate)和数据源方法的隐私,您仍然可以选择创建另一个类来处理您的 tableview 数据源内容

例如

class IceCreamListDataSource: NSObject, UITableViewDataSource
{
let dataStore = IceCreamStore()

// MARK: - Table view data source

func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return dataStore.allFlavors().count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let flavor = dataStore.allFlavors()[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier("IceCreamListCell", forIndexPath: indexPath)
cell.textLabel?.text = flavor
return cell
}
}

现在在您的 ViewControllerUITableViewController 类中,您可以使用此类作为数据源

class IceCreamListViewController: UITableViewController
{
let dataSource = IceCreamListDataSource()

// MARK: - View lifecycle

override func viewDidLoad()
{
super.viewDidLoad()
tableView.dataSource = dataSource
}
}

希望对你有帮助

关于ios - 如何防止访问其他类的委托(delegate)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48762960/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com