Printing Contents of TableView in Swift IOS Application












-1














I am making an app with a scene that contains a tableview. Each cell in the table view contains a rating control (made up of 5 stars) and a label. At the click of a button I would like to print all of the labels as well as the number of stars that user has clicked from the rating controls from the entire table view. to the console.



How can I do this?



Here is my tableview(_:cellForRowAt:) method



override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Configure the cell
// Table view cells are reused and should be dequeued using a cell identifier
let cellId = "cell"

guard let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as? MatchingTableViewCell else {
fatalError("The dequeued cell is not an instacne of MatchingTableViewCell")
}

// Fetches the appropriate match for the data source layout.
let match = matching[indexPath.row]

cell.nameLabel.text = match.name
cell.photoImagView.image = match.photo
cell.ratingControl.rating = match.rating

return cell
}


Data model object is an array of structs of Match objects:



import Foundation
import UIKit
import os.log

class Match: NSObject, NSCoding {
// MARK: Properties
var name: String
var photo: UIImage?
var rating: Int


// MARK: Archiving Paths
static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first
static let ArchiveURL = DocumentsDirectory?.appendingPathComponent("matching")

// MARK: Types
struct PropertyKey {
static let name = "name"
static let photo = "photo"
static let rating = "rating"
}

init?(name: String, photo: UIImage?, rating: Int) {
// The name must not be empty
guard !name.isEmpty else{
return nil
}
// The rating must be between 0 and 5 inclusively
guard (rating >= 0) && (rating <= 5) else {
return nil
}
// Initialize stored properties
self.name = name
self.photo = photo
self.rating = rating
}

override var description : String {
return "rating (self.rating) n"
}
// MARK: NSCoding
func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: PropertyKey.name)
aCoder.encode(photo, forKey: PropertyKey.photo)
aCoder.encode(rating, forKey: PropertyKey.rating)

}

required convenience init?(coder aDecoder: NSCoder) {
// The name is required if we cannot decode a name string, the init should fail
guard let name = aDecoder.decodeObject(forKey: PropertyKey.name) as? String else{
os_log("Unable to decode the name for a Match object", log: OSLog.default, type: .debug)
return nil
}
// Because the photo is an optional property of Match, just use conditional cast.
let photo = aDecoder.decodeObject(forKey: PropertyKey.photo) as? UIImage
let rating = aDecoder.decodeObject(forKey: PropertyKey.rating)

// Must call designated init
self.init(name: name, photo: photo, rating: rating as! Int)

}


}



RatingControl.swiift:



import UIKit

@IBDesignable class RatingControl: UIStackView {



// MARK: Properties
private var ratingButtons = [UIButton]()
var rating = 0 {
didSet {
updateButtonSelectionStates()
}
}

@IBInspectable var starSize: CGSize = CGSize(width: 44.0, height: 44.0) {// Defines size of buttons/
didSet{
setupButtons()
}
}

@IBInspectable var starCount: Int = 5 {// Defines number of buttons
didSet{
setupButtons()
}
}

// MARK: Initialization
override init(frame: CGRect) {
super.init(frame: frame)
setupButtons()
}

required init(coder: NSCoder) {
super.init(coder: coder)
setupButtons()
}

// MARK: Private Methods
private func setupButtons(){


// Clear any existing buttons
for button in ratingButtons{
removeArrangedSubview(button)
button.removeFromSuperview()
}
ratingButtons.removeAll()

// Load Button Images
let bundle = Bundle(for: type(of: self))
let filledStar = UIImage(named: "filledStar", in: bundle, compatibleWith: self.traitCollection)
let emptyStar = UIImage(named: "emptyStar", in: bundle, compatibleWith: self.traitCollection)
let highligtedStar = UIImage(named: "highlightedStar", in: bundle, compatibleWith: self.traitCollection)

for _ in 0..<starCount {
// Create the button
let button = UIButton()

// Set the button images
button.setImage(emptyStar, for: .normal)
button.setImage(filledStar, for: .selected)
button.setImage(highligtedStar, for: .highlighted)
button.setImage(highligtedStar, for: [.highlighted, .selected])

// Adding constraints
button.translatesAutoresizingMaskIntoConstraints = false // disables buttons automatically generated constraints
button.heightAnchor.constraint(equalToConstant: starSize.height).isActive = true // defines height
button.widthAnchor.constraint(equalToConstant: starSize.width).isActive = true // defines width

//Setup the button action
button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(button:)), for: .touchUpInside)

// Add button to stack
addArrangedSubview(button)

// Add the new button to the rating button Array
ratingButtons.append(button)
}
updateButtonSelectionStates()
}

// MARK: Button Action
@objc func ratingButtonTapped(button:UIButton){

guard let index = ratingButtons.index(of: button) else {
fatalError("The button, (button), is not in the ratingButtons array: (ratingButtons)")
}
// Calculate the rating of the selected button
let selectedRating = index + 1
if selectedRating == rating { // If the selected star represents the current rating, reset the rating to 0
rating = 0
} else{
// Otherwise set the rating to the selected star
rating = selectedRating
}
}
private func updateButtonSelectionStates() { // Update buttons appearance
for (index, button) in ratingButtons.enumerated() {
// If the index of a button is less than the rating, that button should be selected
button.isSelected = index < rating
}
}


}










share|improve this question





























    -1














    I am making an app with a scene that contains a tableview. Each cell in the table view contains a rating control (made up of 5 stars) and a label. At the click of a button I would like to print all of the labels as well as the number of stars that user has clicked from the rating controls from the entire table view. to the console.



    How can I do this?



    Here is my tableview(_:cellForRowAt:) method



    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    // Configure the cell
    // Table view cells are reused and should be dequeued using a cell identifier
    let cellId = "cell"

    guard let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as? MatchingTableViewCell else {
    fatalError("The dequeued cell is not an instacne of MatchingTableViewCell")
    }

    // Fetches the appropriate match for the data source layout.
    let match = matching[indexPath.row]

    cell.nameLabel.text = match.name
    cell.photoImagView.image = match.photo
    cell.ratingControl.rating = match.rating

    return cell
    }


    Data model object is an array of structs of Match objects:



    import Foundation
    import UIKit
    import os.log

    class Match: NSObject, NSCoding {
    // MARK: Properties
    var name: String
    var photo: UIImage?
    var rating: Int


    // MARK: Archiving Paths
    static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first
    static let ArchiveURL = DocumentsDirectory?.appendingPathComponent("matching")

    // MARK: Types
    struct PropertyKey {
    static let name = "name"
    static let photo = "photo"
    static let rating = "rating"
    }

    init?(name: String, photo: UIImage?, rating: Int) {
    // The name must not be empty
    guard !name.isEmpty else{
    return nil
    }
    // The rating must be between 0 and 5 inclusively
    guard (rating >= 0) && (rating <= 5) else {
    return nil
    }
    // Initialize stored properties
    self.name = name
    self.photo = photo
    self.rating = rating
    }

    override var description : String {
    return "rating (self.rating) n"
    }
    // MARK: NSCoding
    func encode(with aCoder: NSCoder) {
    aCoder.encode(name, forKey: PropertyKey.name)
    aCoder.encode(photo, forKey: PropertyKey.photo)
    aCoder.encode(rating, forKey: PropertyKey.rating)

    }

    required convenience init?(coder aDecoder: NSCoder) {
    // The name is required if we cannot decode a name string, the init should fail
    guard let name = aDecoder.decodeObject(forKey: PropertyKey.name) as? String else{
    os_log("Unable to decode the name for a Match object", log: OSLog.default, type: .debug)
    return nil
    }
    // Because the photo is an optional property of Match, just use conditional cast.
    let photo = aDecoder.decodeObject(forKey: PropertyKey.photo) as? UIImage
    let rating = aDecoder.decodeObject(forKey: PropertyKey.rating)

    // Must call designated init
    self.init(name: name, photo: photo, rating: rating as! Int)

    }


    }



    RatingControl.swiift:



    import UIKit

    @IBDesignable class RatingControl: UIStackView {



    // MARK: Properties
    private var ratingButtons = [UIButton]()
    var rating = 0 {
    didSet {
    updateButtonSelectionStates()
    }
    }

    @IBInspectable var starSize: CGSize = CGSize(width: 44.0, height: 44.0) {// Defines size of buttons/
    didSet{
    setupButtons()
    }
    }

    @IBInspectable var starCount: Int = 5 {// Defines number of buttons
    didSet{
    setupButtons()
    }
    }

    // MARK: Initialization
    override init(frame: CGRect) {
    super.init(frame: frame)
    setupButtons()
    }

    required init(coder: NSCoder) {
    super.init(coder: coder)
    setupButtons()
    }

    // MARK: Private Methods
    private func setupButtons(){


    // Clear any existing buttons
    for button in ratingButtons{
    removeArrangedSubview(button)
    button.removeFromSuperview()
    }
    ratingButtons.removeAll()

    // Load Button Images
    let bundle = Bundle(for: type(of: self))
    let filledStar = UIImage(named: "filledStar", in: bundle, compatibleWith: self.traitCollection)
    let emptyStar = UIImage(named: "emptyStar", in: bundle, compatibleWith: self.traitCollection)
    let highligtedStar = UIImage(named: "highlightedStar", in: bundle, compatibleWith: self.traitCollection)

    for _ in 0..<starCount {
    // Create the button
    let button = UIButton()

    // Set the button images
    button.setImage(emptyStar, for: .normal)
    button.setImage(filledStar, for: .selected)
    button.setImage(highligtedStar, for: .highlighted)
    button.setImage(highligtedStar, for: [.highlighted, .selected])

    // Adding constraints
    button.translatesAutoresizingMaskIntoConstraints = false // disables buttons automatically generated constraints
    button.heightAnchor.constraint(equalToConstant: starSize.height).isActive = true // defines height
    button.widthAnchor.constraint(equalToConstant: starSize.width).isActive = true // defines width

    //Setup the button action
    button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(button:)), for: .touchUpInside)

    // Add button to stack
    addArrangedSubview(button)

    // Add the new button to the rating button Array
    ratingButtons.append(button)
    }
    updateButtonSelectionStates()
    }

    // MARK: Button Action
    @objc func ratingButtonTapped(button:UIButton){

    guard let index = ratingButtons.index(of: button) else {
    fatalError("The button, (button), is not in the ratingButtons array: (ratingButtons)")
    }
    // Calculate the rating of the selected button
    let selectedRating = index + 1
    if selectedRating == rating { // If the selected star represents the current rating, reset the rating to 0
    rating = 0
    } else{
    // Otherwise set the rating to the selected star
    rating = selectedRating
    }
    }
    private func updateButtonSelectionStates() { // Update buttons appearance
    for (index, button) in ratingButtons.enumerated() {
    // If the index of a button is less than the rating, that button should be selected
    button.isSelected = index < rating
    }
    }


    }










    share|improve this question



























      -1












      -1








      -1







      I am making an app with a scene that contains a tableview. Each cell in the table view contains a rating control (made up of 5 stars) and a label. At the click of a button I would like to print all of the labels as well as the number of stars that user has clicked from the rating controls from the entire table view. to the console.



      How can I do this?



      Here is my tableview(_:cellForRowAt:) method



      override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      // Configure the cell
      // Table view cells are reused and should be dequeued using a cell identifier
      let cellId = "cell"

      guard let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as? MatchingTableViewCell else {
      fatalError("The dequeued cell is not an instacne of MatchingTableViewCell")
      }

      // Fetches the appropriate match for the data source layout.
      let match = matching[indexPath.row]

      cell.nameLabel.text = match.name
      cell.photoImagView.image = match.photo
      cell.ratingControl.rating = match.rating

      return cell
      }


      Data model object is an array of structs of Match objects:



      import Foundation
      import UIKit
      import os.log

      class Match: NSObject, NSCoding {
      // MARK: Properties
      var name: String
      var photo: UIImage?
      var rating: Int


      // MARK: Archiving Paths
      static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first
      static let ArchiveURL = DocumentsDirectory?.appendingPathComponent("matching")

      // MARK: Types
      struct PropertyKey {
      static let name = "name"
      static let photo = "photo"
      static let rating = "rating"
      }

      init?(name: String, photo: UIImage?, rating: Int) {
      // The name must not be empty
      guard !name.isEmpty else{
      return nil
      }
      // The rating must be between 0 and 5 inclusively
      guard (rating >= 0) && (rating <= 5) else {
      return nil
      }
      // Initialize stored properties
      self.name = name
      self.photo = photo
      self.rating = rating
      }

      override var description : String {
      return "rating (self.rating) n"
      }
      // MARK: NSCoding
      func encode(with aCoder: NSCoder) {
      aCoder.encode(name, forKey: PropertyKey.name)
      aCoder.encode(photo, forKey: PropertyKey.photo)
      aCoder.encode(rating, forKey: PropertyKey.rating)

      }

      required convenience init?(coder aDecoder: NSCoder) {
      // The name is required if we cannot decode a name string, the init should fail
      guard let name = aDecoder.decodeObject(forKey: PropertyKey.name) as? String else{
      os_log("Unable to decode the name for a Match object", log: OSLog.default, type: .debug)
      return nil
      }
      // Because the photo is an optional property of Match, just use conditional cast.
      let photo = aDecoder.decodeObject(forKey: PropertyKey.photo) as? UIImage
      let rating = aDecoder.decodeObject(forKey: PropertyKey.rating)

      // Must call designated init
      self.init(name: name, photo: photo, rating: rating as! Int)

      }


      }



      RatingControl.swiift:



      import UIKit

      @IBDesignable class RatingControl: UIStackView {



      // MARK: Properties
      private var ratingButtons = [UIButton]()
      var rating = 0 {
      didSet {
      updateButtonSelectionStates()
      }
      }

      @IBInspectable var starSize: CGSize = CGSize(width: 44.0, height: 44.0) {// Defines size of buttons/
      didSet{
      setupButtons()
      }
      }

      @IBInspectable var starCount: Int = 5 {// Defines number of buttons
      didSet{
      setupButtons()
      }
      }

      // MARK: Initialization
      override init(frame: CGRect) {
      super.init(frame: frame)
      setupButtons()
      }

      required init(coder: NSCoder) {
      super.init(coder: coder)
      setupButtons()
      }

      // MARK: Private Methods
      private func setupButtons(){


      // Clear any existing buttons
      for button in ratingButtons{
      removeArrangedSubview(button)
      button.removeFromSuperview()
      }
      ratingButtons.removeAll()

      // Load Button Images
      let bundle = Bundle(for: type(of: self))
      let filledStar = UIImage(named: "filledStar", in: bundle, compatibleWith: self.traitCollection)
      let emptyStar = UIImage(named: "emptyStar", in: bundle, compatibleWith: self.traitCollection)
      let highligtedStar = UIImage(named: "highlightedStar", in: bundle, compatibleWith: self.traitCollection)

      for _ in 0..<starCount {
      // Create the button
      let button = UIButton()

      // Set the button images
      button.setImage(emptyStar, for: .normal)
      button.setImage(filledStar, for: .selected)
      button.setImage(highligtedStar, for: .highlighted)
      button.setImage(highligtedStar, for: [.highlighted, .selected])

      // Adding constraints
      button.translatesAutoresizingMaskIntoConstraints = false // disables buttons automatically generated constraints
      button.heightAnchor.constraint(equalToConstant: starSize.height).isActive = true // defines height
      button.widthAnchor.constraint(equalToConstant: starSize.width).isActive = true // defines width

      //Setup the button action
      button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(button:)), for: .touchUpInside)

      // Add button to stack
      addArrangedSubview(button)

      // Add the new button to the rating button Array
      ratingButtons.append(button)
      }
      updateButtonSelectionStates()
      }

      // MARK: Button Action
      @objc func ratingButtonTapped(button:UIButton){

      guard let index = ratingButtons.index(of: button) else {
      fatalError("The button, (button), is not in the ratingButtons array: (ratingButtons)")
      }
      // Calculate the rating of the selected button
      let selectedRating = index + 1
      if selectedRating == rating { // If the selected star represents the current rating, reset the rating to 0
      rating = 0
      } else{
      // Otherwise set the rating to the selected star
      rating = selectedRating
      }
      }
      private func updateButtonSelectionStates() { // Update buttons appearance
      for (index, button) in ratingButtons.enumerated() {
      // If the index of a button is less than the rating, that button should be selected
      button.isSelected = index < rating
      }
      }


      }










      share|improve this question















      I am making an app with a scene that contains a tableview. Each cell in the table view contains a rating control (made up of 5 stars) and a label. At the click of a button I would like to print all of the labels as well as the number of stars that user has clicked from the rating controls from the entire table view. to the console.



      How can I do this?



      Here is my tableview(_:cellForRowAt:) method



      override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      // Configure the cell
      // Table view cells are reused and should be dequeued using a cell identifier
      let cellId = "cell"

      guard let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as? MatchingTableViewCell else {
      fatalError("The dequeued cell is not an instacne of MatchingTableViewCell")
      }

      // Fetches the appropriate match for the data source layout.
      let match = matching[indexPath.row]

      cell.nameLabel.text = match.name
      cell.photoImagView.image = match.photo
      cell.ratingControl.rating = match.rating

      return cell
      }


      Data model object is an array of structs of Match objects:



      import Foundation
      import UIKit
      import os.log

      class Match: NSObject, NSCoding {
      // MARK: Properties
      var name: String
      var photo: UIImage?
      var rating: Int


      // MARK: Archiving Paths
      static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first
      static let ArchiveURL = DocumentsDirectory?.appendingPathComponent("matching")

      // MARK: Types
      struct PropertyKey {
      static let name = "name"
      static let photo = "photo"
      static let rating = "rating"
      }

      init?(name: String, photo: UIImage?, rating: Int) {
      // The name must not be empty
      guard !name.isEmpty else{
      return nil
      }
      // The rating must be between 0 and 5 inclusively
      guard (rating >= 0) && (rating <= 5) else {
      return nil
      }
      // Initialize stored properties
      self.name = name
      self.photo = photo
      self.rating = rating
      }

      override var description : String {
      return "rating (self.rating) n"
      }
      // MARK: NSCoding
      func encode(with aCoder: NSCoder) {
      aCoder.encode(name, forKey: PropertyKey.name)
      aCoder.encode(photo, forKey: PropertyKey.photo)
      aCoder.encode(rating, forKey: PropertyKey.rating)

      }

      required convenience init?(coder aDecoder: NSCoder) {
      // The name is required if we cannot decode a name string, the init should fail
      guard let name = aDecoder.decodeObject(forKey: PropertyKey.name) as? String else{
      os_log("Unable to decode the name for a Match object", log: OSLog.default, type: .debug)
      return nil
      }
      // Because the photo is an optional property of Match, just use conditional cast.
      let photo = aDecoder.decodeObject(forKey: PropertyKey.photo) as? UIImage
      let rating = aDecoder.decodeObject(forKey: PropertyKey.rating)

      // Must call designated init
      self.init(name: name, photo: photo, rating: rating as! Int)

      }


      }



      RatingControl.swiift:



      import UIKit

      @IBDesignable class RatingControl: UIStackView {



      // MARK: Properties
      private var ratingButtons = [UIButton]()
      var rating = 0 {
      didSet {
      updateButtonSelectionStates()
      }
      }

      @IBInspectable var starSize: CGSize = CGSize(width: 44.0, height: 44.0) {// Defines size of buttons/
      didSet{
      setupButtons()
      }
      }

      @IBInspectable var starCount: Int = 5 {// Defines number of buttons
      didSet{
      setupButtons()
      }
      }

      // MARK: Initialization
      override init(frame: CGRect) {
      super.init(frame: frame)
      setupButtons()
      }

      required init(coder: NSCoder) {
      super.init(coder: coder)
      setupButtons()
      }

      // MARK: Private Methods
      private func setupButtons(){


      // Clear any existing buttons
      for button in ratingButtons{
      removeArrangedSubview(button)
      button.removeFromSuperview()
      }
      ratingButtons.removeAll()

      // Load Button Images
      let bundle = Bundle(for: type(of: self))
      let filledStar = UIImage(named: "filledStar", in: bundle, compatibleWith: self.traitCollection)
      let emptyStar = UIImage(named: "emptyStar", in: bundle, compatibleWith: self.traitCollection)
      let highligtedStar = UIImage(named: "highlightedStar", in: bundle, compatibleWith: self.traitCollection)

      for _ in 0..<starCount {
      // Create the button
      let button = UIButton()

      // Set the button images
      button.setImage(emptyStar, for: .normal)
      button.setImage(filledStar, for: .selected)
      button.setImage(highligtedStar, for: .highlighted)
      button.setImage(highligtedStar, for: [.highlighted, .selected])

      // Adding constraints
      button.translatesAutoresizingMaskIntoConstraints = false // disables buttons automatically generated constraints
      button.heightAnchor.constraint(equalToConstant: starSize.height).isActive = true // defines height
      button.widthAnchor.constraint(equalToConstant: starSize.width).isActive = true // defines width

      //Setup the button action
      button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(button:)), for: .touchUpInside)

      // Add button to stack
      addArrangedSubview(button)

      // Add the new button to the rating button Array
      ratingButtons.append(button)
      }
      updateButtonSelectionStates()
      }

      // MARK: Button Action
      @objc func ratingButtonTapped(button:UIButton){

      guard let index = ratingButtons.index(of: button) else {
      fatalError("The button, (button), is not in the ratingButtons array: (ratingButtons)")
      }
      // Calculate the rating of the selected button
      let selectedRating = index + 1
      if selectedRating == rating { // If the selected star represents the current rating, reset the rating to 0
      rating = 0
      } else{
      // Otherwise set the rating to the selected star
      rating = selectedRating
      }
      }
      private func updateButtonSelectionStates() { // Update buttons appearance
      for (index, button) in ratingButtons.enumerated() {
      // If the index of a button is less than the rating, that button should be selected
      button.isSelected = index < rating
      }
      }


      }







      ios swift uitableview






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 25 '18 at 16:00

























      asked Nov 22 '18 at 23:07









      Kann

      64




      64
























          1 Answer
          1






          active

          oldest

          votes


















          0














          You've got this wrong. Your table view does not save data, it displays it. You want to have a data model that holds the values you display from your table view. That's what feeds your tableView dataSource methods. Often it will be an array of structs.



          You want to print the contents of your table view's data model.



          Edit:



          Now that you've provided that info we can help you.



          Add CustomStringConvertible conformance to your data model:



          class Match: NSObject, NSCoding, CustomStringConvertible  {


          The only requirement for CustomStringConvertible is that you provide a computed property description that's a String:



          var description: String {
          return "Match(name:(name),rating:(rating))"
          }


          Then in your button action



          @IBAction func logInfo(sender: UIButton) {
          matching.forEach { print($0) }
          }


          Since your Match class now conforms to CustomStringConvertible, you can print Match objects directly.



          Or if you want indexes:



          @IBAction func logInfo(sender: UIButton) {
          matching.enumerated()forEach { print(String(format:"%02l", $0.0) + ": " + $0.1) }
          }





          share|improve this answer























          • I am asking how to do that. You're just restating what I asked.
            – Kann
            Nov 23 '18 at 21:26










          • In order to help you with that you will need to edit your question and add your data model object, and perhaps your tableview(_:cellForRowAt:) method.
            – Duncan C
            Nov 23 '18 at 22:14










          • I have updated the question with the requested information.
            – Kann
            Nov 24 '18 at 3:50










          • See the edit to my answer.
            – Duncan C
            Nov 24 '18 at 12:36










          • Okay, this prints them out but it always says the rating is 5 even if a different amount of stars is selected.
            – Kann
            Nov 24 '18 at 21:54











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53438927%2fprinting-contents-of-tableview-in-swift-ios-application%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          You've got this wrong. Your table view does not save data, it displays it. You want to have a data model that holds the values you display from your table view. That's what feeds your tableView dataSource methods. Often it will be an array of structs.



          You want to print the contents of your table view's data model.



          Edit:



          Now that you've provided that info we can help you.



          Add CustomStringConvertible conformance to your data model:



          class Match: NSObject, NSCoding, CustomStringConvertible  {


          The only requirement for CustomStringConvertible is that you provide a computed property description that's a String:



          var description: String {
          return "Match(name:(name),rating:(rating))"
          }


          Then in your button action



          @IBAction func logInfo(sender: UIButton) {
          matching.forEach { print($0) }
          }


          Since your Match class now conforms to CustomStringConvertible, you can print Match objects directly.



          Or if you want indexes:



          @IBAction func logInfo(sender: UIButton) {
          matching.enumerated()forEach { print(String(format:"%02l", $0.0) + ": " + $0.1) }
          }





          share|improve this answer























          • I am asking how to do that. You're just restating what I asked.
            – Kann
            Nov 23 '18 at 21:26










          • In order to help you with that you will need to edit your question and add your data model object, and perhaps your tableview(_:cellForRowAt:) method.
            – Duncan C
            Nov 23 '18 at 22:14










          • I have updated the question with the requested information.
            – Kann
            Nov 24 '18 at 3:50










          • See the edit to my answer.
            – Duncan C
            Nov 24 '18 at 12:36










          • Okay, this prints them out but it always says the rating is 5 even if a different amount of stars is selected.
            – Kann
            Nov 24 '18 at 21:54
















          0














          You've got this wrong. Your table view does not save data, it displays it. You want to have a data model that holds the values you display from your table view. That's what feeds your tableView dataSource methods. Often it will be an array of structs.



          You want to print the contents of your table view's data model.



          Edit:



          Now that you've provided that info we can help you.



          Add CustomStringConvertible conformance to your data model:



          class Match: NSObject, NSCoding, CustomStringConvertible  {


          The only requirement for CustomStringConvertible is that you provide a computed property description that's a String:



          var description: String {
          return "Match(name:(name),rating:(rating))"
          }


          Then in your button action



          @IBAction func logInfo(sender: UIButton) {
          matching.forEach { print($0) }
          }


          Since your Match class now conforms to CustomStringConvertible, you can print Match objects directly.



          Or if you want indexes:



          @IBAction func logInfo(sender: UIButton) {
          matching.enumerated()forEach { print(String(format:"%02l", $0.0) + ": " + $0.1) }
          }





          share|improve this answer























          • I am asking how to do that. You're just restating what I asked.
            – Kann
            Nov 23 '18 at 21:26










          • In order to help you with that you will need to edit your question and add your data model object, and perhaps your tableview(_:cellForRowAt:) method.
            – Duncan C
            Nov 23 '18 at 22:14










          • I have updated the question with the requested information.
            – Kann
            Nov 24 '18 at 3:50










          • See the edit to my answer.
            – Duncan C
            Nov 24 '18 at 12:36










          • Okay, this prints them out but it always says the rating is 5 even if a different amount of stars is selected.
            – Kann
            Nov 24 '18 at 21:54














          0












          0








          0






          You've got this wrong. Your table view does not save data, it displays it. You want to have a data model that holds the values you display from your table view. That's what feeds your tableView dataSource methods. Often it will be an array of structs.



          You want to print the contents of your table view's data model.



          Edit:



          Now that you've provided that info we can help you.



          Add CustomStringConvertible conformance to your data model:



          class Match: NSObject, NSCoding, CustomStringConvertible  {


          The only requirement for CustomStringConvertible is that you provide a computed property description that's a String:



          var description: String {
          return "Match(name:(name),rating:(rating))"
          }


          Then in your button action



          @IBAction func logInfo(sender: UIButton) {
          matching.forEach { print($0) }
          }


          Since your Match class now conforms to CustomStringConvertible, you can print Match objects directly.



          Or if you want indexes:



          @IBAction func logInfo(sender: UIButton) {
          matching.enumerated()forEach { print(String(format:"%02l", $0.0) + ": " + $0.1) }
          }





          share|improve this answer














          You've got this wrong. Your table view does not save data, it displays it. You want to have a data model that holds the values you display from your table view. That's what feeds your tableView dataSource methods. Often it will be an array of structs.



          You want to print the contents of your table view's data model.



          Edit:



          Now that you've provided that info we can help you.



          Add CustomStringConvertible conformance to your data model:



          class Match: NSObject, NSCoding, CustomStringConvertible  {


          The only requirement for CustomStringConvertible is that you provide a computed property description that's a String:



          var description: String {
          return "Match(name:(name),rating:(rating))"
          }


          Then in your button action



          @IBAction func logInfo(sender: UIButton) {
          matching.forEach { print($0) }
          }


          Since your Match class now conforms to CustomStringConvertible, you can print Match objects directly.



          Or if you want indexes:



          @IBAction func logInfo(sender: UIButton) {
          matching.enumerated()forEach { print(String(format:"%02l", $0.0) + ": " + $0.1) }
          }






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 24 '18 at 12:35

























          answered Nov 23 '18 at 0:45









          Duncan C

          92.1k13114196




          92.1k13114196












          • I am asking how to do that. You're just restating what I asked.
            – Kann
            Nov 23 '18 at 21:26










          • In order to help you with that you will need to edit your question and add your data model object, and perhaps your tableview(_:cellForRowAt:) method.
            – Duncan C
            Nov 23 '18 at 22:14










          • I have updated the question with the requested information.
            – Kann
            Nov 24 '18 at 3:50










          • See the edit to my answer.
            – Duncan C
            Nov 24 '18 at 12:36










          • Okay, this prints them out but it always says the rating is 5 even if a different amount of stars is selected.
            – Kann
            Nov 24 '18 at 21:54


















          • I am asking how to do that. You're just restating what I asked.
            – Kann
            Nov 23 '18 at 21:26










          • In order to help you with that you will need to edit your question and add your data model object, and perhaps your tableview(_:cellForRowAt:) method.
            – Duncan C
            Nov 23 '18 at 22:14










          • I have updated the question with the requested information.
            – Kann
            Nov 24 '18 at 3:50










          • See the edit to my answer.
            – Duncan C
            Nov 24 '18 at 12:36










          • Okay, this prints them out but it always says the rating is 5 even if a different amount of stars is selected.
            – Kann
            Nov 24 '18 at 21:54
















          I am asking how to do that. You're just restating what I asked.
          – Kann
          Nov 23 '18 at 21:26




          I am asking how to do that. You're just restating what I asked.
          – Kann
          Nov 23 '18 at 21:26












          In order to help you with that you will need to edit your question and add your data model object, and perhaps your tableview(_:cellForRowAt:) method.
          – Duncan C
          Nov 23 '18 at 22:14




          In order to help you with that you will need to edit your question and add your data model object, and perhaps your tableview(_:cellForRowAt:) method.
          – Duncan C
          Nov 23 '18 at 22:14












          I have updated the question with the requested information.
          – Kann
          Nov 24 '18 at 3:50




          I have updated the question with the requested information.
          – Kann
          Nov 24 '18 at 3:50












          See the edit to my answer.
          – Duncan C
          Nov 24 '18 at 12:36




          See the edit to my answer.
          – Duncan C
          Nov 24 '18 at 12:36












          Okay, this prints them out but it always says the rating is 5 even if a different amount of stars is selected.
          – Kann
          Nov 24 '18 at 21:54




          Okay, this prints them out but it always says the rating is 5 even if a different amount of stars is selected.
          – Kann
          Nov 24 '18 at 21:54


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53438927%2fprinting-contents-of-tableview-in-swift-ios-application%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Berounka

          Sphinx de Gizeh

          Different font size/position of beamer's navigation symbols template's content depending on regular/plain...