【问题标题】:How do I access an array in an array of class instances?如何访问类实例数组中的数组?
【发布时间】:2016-09-12 00:50:12
【问题描述】:

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

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 
}

在我的 Category 类中,我有一个为类别分配值的方法,这样我就可以将它们排除在视图控制器之外。该方法列举如下:

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

在我的一个 tableview 控制器文件中,我试图通过将其设置为 getCategories 方法中主题的主题计数来获取部分中的行数。尽管我能够在 getCategories 方法中获得类别的计数,但我所做的任何事情似乎都不起作用……我似乎无法专门访问主题数组。

这是我为获得类别计数所做的工作......

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

我需要这样做,除非我需要获取我在 getCategories 方法中设置的主题的计数。

非常感谢! :)

【问题讨论】:

  • return categories[section].topics.count

标签: ios arrays swift class tableview


【解决方案1】:

我认为您缺少的部分是您需要知道要从哪个部分获取主题计数。这应该由表视图数据源回调以某种方式提供给您。

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
}

【讨论】:

    【解决方案2】:

    由于categoriesCategory 对象的数组,您需要访问正确的索引,然后是主题数组并获取计数:

    categories[section].topics.count
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-09
      • 2017-10-08
      • 2016-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-16
      相关资源
      最近更新 更多