Mohammad Alikhani
Mohammad Alikhani

Reputation: 191

unexpectedly found nil while unwrapping an Optional values access tableView Cell

I want to access cell of tableView from outside tableView func, for example in this case I want to access from a IBAction Func, then I have created tableView object and IndexPath object, when I running my project the Xcode shows me this error:

Fatal error: unexpectedly found nil while unwrapping an Optional values

for this line: mytableView!.cellForRowAtIndexPath(indexPath!)

@IBAction func editButtonFunc(sender: AnyObject) {

    mytableView!.cellForRowAtIndexPath(indexPath!)
    let cell =
    mytableView!.dequeueReusableCellWithIdentifier(
        "mycell", forIndexPath: indexPath!)
        as! profileTableViewCell
    cell.contentOutlet.text = contentItems[indexPath!.row]
    cell.contentOutlet.textAlignment = NSTextAlignment.Right
    cell.contentOutlet.font = UIFont(name: "X Yekan", size: 18)

}

Upvotes: 1

Views: 307

Answers (3)

gnasher729
gnasher729

Reputation: 52538

Calling the tableview method cellForRowAtIndexPath is almost always wrong. It will return nil if the index path is not for a cell that is visible on the screen. Your case is worse because you call the function and then don't use its value. What is absolutely, totally wrong is calling dequeue.... from anywhere other than your own delegate cellForRowAtIndexPath.

Upvotes: 0

Abhinav
Abhinav

Reputation: 38142

Clearly either mytableView or indexPath is nil when you are trying to unwrap it. You must check both these objects holds right value before you force unwrap them.

Upvotes: 0

liushuaikobe
liushuaikobe

Reputation: 2190

If you just want to get the ref of some cell, perhaps you need:

func getTableViewCell() -> UITableViewCell? {
    guard let tableView = mytableView, index = indexPath 
    else { return nil }

    return tableView.cellForRowAtIndexPath(index)
}

And, If you want to set data for the tableViewCell, you should do this in the UITableViewDataSource methods: cellForRowAtIndexPath.

Upvotes: 0

Related Questions