0

I'm creating a tableView from a set of different inheritance classes, but i can't seem to figure out what is the best way to add them all in to a tableView, without creating multiple arrays, which isn't ideal?

Lets for instance take a classic example, how would i be able to add multiple different cat and dog objects into an tableView? what is the best way to do this?

class Pet {
    var id: Int = 0
    var name: String = ""

}

class Dog: Pet {
    var Type: String = ""
}

class Cat: Pet {
    var Type: String = ""
}
Peter Pik
  • 11,023
  • 19
  • 84
  • 142

1 Answers1

0

The most straightforward way is to reflect your model in your UI layer. Like:

class PetTableViewCell {
}

class DogTableViewCell: PetTableViewCell {
}

class CatTableViewCell: PetTableViewCell {
}

And use then them in your table view: this answer shows usage of two different cell types in UITableView

Another approach is to define a protocol which describes behaviour needed from model class to be displayed in the cell, and implement it (or inherit it) in model classes.

protocol MyTableViewCellDisplayable {
    var Type: String
    var Pic: Image
    var Name: String
}

class MyTableViewCell {
    func displayObject(obj: MyTableViewCellDisplayable);
}

class Pet: MyTableViewCellDisplayable {
}

class Dog: Pet {
}

class Cat: Pet {
}
...

The choice of right solution really depends on your particular requirements.

Community
  • 1
  • 1
Petro Korienev
  • 4,007
  • 6
  • 34
  • 43
  • all data in the tableView will be from the Pet class and not from subclass, is it then necessary to make subclasses? – Peter Pik Sep 27 '15 at 09:34
  • No - from subclasses as well. They will inherit protocol implementation, probably use without modification, probably override it. – Petro Korienev Sep 27 '15 at 09:38
  • y okay i guess the main problem is going to be for instance sorting these different objects by for instance a date in the Pet Object? – Peter Pik Sep 27 '15 at 09:39
  • No - you can put everything you want to display in something like Array and sort by some property common for all model classes - better to define it in protocol as well. For sorting you might use http://stackoverflow.com/questions/24130026/swift-how-to-sort-array-of-custom-objects-by-property-value – Petro Korienev Sep 27 '15 at 09:47
  • MyTableViewCellDisplayable is a tableViewCell subclass? – Peter Pik Sep 27 '15 at 09:52
  • MyTableViewCellDisplayable is a protocol, MyTableViewCell is UITableViewCell subclass – Petro Korienev Sep 27 '15 at 09:54
  • `MyTableViewCellDisplayable` is at the moment undeclared, what do i need to declare here? sorry haven't work with this before? any guides on this or? – Peter Pik Sep 27 '15 at 09:55
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/90725/discussion-between-petro-korienev-and-peter-pik). – Petro Korienev Sep 27 '15 at 09:56