4

The app crashes at the line enter image description here

class ImageValueCell: UITableViewCell, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var imagesList: UITableView!
  var imageArray: NSArray!

override func awakeFromNib() {
    //super.awakeFromNib()
    // Initialization code
    imagesList.delegate = self;
    imagesList.dataSource = self;
    imageArray = NSArray()
    imagesList.reloadData()
}

func addImagesValue(objectList: NSMutableArray, machine: WIFIMachine){
    imageArray = objectList
    imagesList.reloadData() //CRASHED HERE
  }

}

I trace through and found that imageList is nil when the crash happens. This is a custom cell with a UITableView created on the storyboard. Can anyone advise me on the possible solution that i could try?

Perwyl Liu
  • 339
  • 4
  • 14

1 Answers1

2

If you are calling addImagesValue before the awakeFromNib is called, then your code will empty the array. I don't think that is what you want. Here is a better solution:

class ImageValueCell: UITableViewCell, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var imagesList: UITableView!
    var imageArray: NSArray = NSArray() {
        didSet {
            // whenever the imageArray changes, reload the imagesList
            if let imagesList = imagesList {
                imagesList.reloadData()
            }
        }
    }

    override func awakeFromNib() {
        // why isn't the below done from inside the nib file? That's how I would do it.
        imagesList.delegate = self
        imagesList.dataSource = self
        imagesList.reloadData()
    }

    func addImagesValue(objectList: NSMutableArray, machine: WIFIMachine){
        imageArray = objectList
    }

}
Daniel T.
  • 24,573
  • 4
  • 44
  • 59
  • Hi, i manage to get rid of the error. However ` imagesList.reloadData()` is never called when the size of imageArray increase from 0-1. Table was not reloaded. – Perwyl Liu Dec 05 '14 at 01:53
  • 1
    Base on your original question, that sounds reasonable and expected. If you change the `imageArray` while `imagesList` is `nil`, the `reloadData()` method shouldn't be called. That said, I made a minor change to my answer. – Daniel T. Dec 05 '14 at 01:56