reloadData() fatal error: unexpectedly found nil while unwrapping an Optional value

ε祈祈猫儿з 提交于 2019-12-01 21:00:06

问题


The app crashes at the line

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?


回答1:


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
    }

}


来源:https://stackoverflow.com/questions/27295894/reloaddata-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-va

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!