gpt4 book ai didi

ios - 如何访问类实例数组中的数组?

转载 作者:行者123 更新时间:2023-11-30 13:05:23 24 4
gpt4 key购买 nike

我正在尝试通过创建一个类来表示每个列表项来练习使用模型制作列表应用程序。我有一个 Category 类,其中包含三个属性 - 两个字符串和一个字符串数组。这是类(class):

class Category {

var name: String
var emoji: String
var topics: [String]
// (the getCategories method listed below goes here) //

init(name: String, emoji: String, topics: [String]) {
self.name = name
self.emoji = emoji
self.topics = topics
}

在我的类别类中,我有一个为类别分配值的方法,这样我就可以将它们排除在 View Controller 之外。该方法如下:

class func getCategories() -> [Category]
{
let categories = [Category(name:"cat", emoji:"😸", topics: ["paws","tails", "fur", "pussyfoot","purr", "kitten", "meow"])
]
return categories
}

在我的一个 TableView Controller 文件中,我尝试通过将其设置为 getCategories 方法中主题的主题计数来获取节中的行数。尽管我能够在 getCategories 方法中获取类别的计数,但我所做的似乎都不起作用...我似乎无法专门访问主题数组。

这是我为获取类别计数所做的操作...

    var categories = Category.getCategories()
....
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return categories.count
}

我需要执行此操作,但我需要获取在 getCategories 方法中设置的主题的计数。

非常感谢! :)

最佳答案

我认为您缺少的一点是您需要知道要从哪个部分获取主题计数。出于某种原因,这应该通过 TableView 数据源回调提供给您。

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return categories[section].topics.count
}

此外,当您需要访问特定主题时,系统会向您传递一个 indexPath

func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let topic = categories[indexPath.section].topics[indexPath.row]
let cell = …

return cell
}

关于ios - 如何访问类实例数组中的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39442065/

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