0

I've an ios project with a table view controller scene with custom tableView cells. When I try to set some value to an outlet in the cellForRowAtIndexPath method this error is thrown:

fatal error: unexpectedly found nil while unwrapping an Optional value

The nil value is the outlet reference of my custom tableView cell class.

I can't figure out what is causing this, since I think that I've configured all correctly.

This is the code I'm using:

MyTableViewController

class MyTableViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.registerClass(MyTableViewCell.self, forCellReuseIdentifier: "myTableViewCell")
    }

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("myTableViewCell", forIndexPath: indexPath) as! MyTableViewCell

        cell.myLabel?.text = "22:40"
        return cell
    }
}

MyTableViewCell

class MyTableViewCell: UITableViewCell {
    @IBOutlet var myLabel: UILabel!
}

Part of the source code of the Main.storyboard:

<scene sceneID="lJU-Ak-NqO">
    <objects>
        <tableViewController id="Uep-sz-gtX" customClass="MyTableViewController" customModule="My_App" customModuleProvider="target" sceneMemberID="viewController">
            <tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" id="Ld7-YH-V2O">
                <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
                <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
                <prototypes>
                    <tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" indentationWidth="10" reuseIdentifier="myTableViewCell" id="Xd0-56-JUL" customClass="MyTableViewCell" customModule="My_App" customModuleProvider="target">
                        <rect key="frame" x="0.0" y="28" width="375" height="44"/>
                        <autoresizingMask key="autoresizingMask"/>
                        <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="Xd0-56-JUL" id="Yrq-Di-Pfr">
                            <rect key="frame" x="0.0" y="0.0" width="375" height="43"/>
                            <autoresizingMask key="autoresizingMask"/>
                            <subviews>
                                <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" text="Label" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="og4-63-SRD">
                                    <rect key="frame" x="8" y="11" width="42" height="21"/>
                                    <fontDescription key="fontDescription" type="system" pointSize="17"/>
                                    <color key="textColor" red="0.0" green="0.0" blue="0.0" alpha="1" colorSpace="calibratedRGB"/>
                                    <nil key="highlightedColor"/>
                                </label>
                            </subviews>
                        </tableViewCellContentView>
                        <connections>
                            <outlet property="myLabel" destination="og4-63-SRD" id="YpX-Ia-DK7"/>
                        </connections>
                    </tableViewCell>
                </prototypes>
                <connections>
                    <outlet property="dataSource" destination="Uep-sz-gtX" id="8kh-UV-dfO"/>
                    <outlet property="delegate" destination="Uep-sz-gtX" id="xyW-cf-Nth"/>
                </connections>
            </tableView>
            <simulatedScreenMetrics key="simulatedDestinationMetrics" type="retina47"/>
        </tableViewController>
        <placeholder placeholderIdentifier="IBFirstResponder" id="Xja-Ye-Jqb" userLabel="First Responder" sceneMemberID="firstResponder"/>
    </objects>
    <point key="canvasLocation" x="401.5" y="-563.5"/>
</scene>

I've already checked the storyboard settings for the custom class controller and the custom table view cell class. Even the cell identifier is correct in the xcode attributes inspector.

Another strange behavior is that the label that I've added in my cell prototype isn't visible at all (it has a default test), even if I don't try to set the custom text. Same behavior if I try to resize the prototype cell (it's show at it's default size).

UPDATE As suggested by @dfri, I've created a new example project from scratch and everything works. The only difference between projects is that here I'm using SSASideMenu so I think that it is the cause of this problem.

The code I'm using to show the tableView when the menu item is tapped, is this (as suggested here):

sideMenuViewController?.contentViewController = UINavigationController(rootViewController: (storyBoard.instantiateViewControllerWithIdentifier("MyTableViewController") as? MyTableViewController)!)
sideMenuViewController?.hideMenuViewController()

I'm using this code for other "plain" view but with the table view I've this problem. Any advice is welcome.

lifeisfoo
  • 15,478
  • 6
  • 74
  • 115
  • Make sure IBOutlet in TableViewCell subclass is bind properly. – technerd Dec 29 '15 at 11:39
  • Try to register tablevicell using below code `tableview.registerNib(UINib(nibName: "cell_nib_name", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "cell_identifier");` instead of `self.tableView.registerClass(MyTableViewCell.self, forCellReuseIdentifier: "myTableViewCell")` – Muthu Selvam Dec 29 '15 at 12:06
  • If the cell class was written in code, the registration is performed using the registerClass: method of UICollectionView, otherwise use registerNib – Muthu Selvam Dec 29 '15 at 12:15
  • I've solved following [this answer](http://stackoverflow.com/a/20132836/3340702). Was an outlet trouble. – lifeisfoo Dec 30 '15 at 08:33

1 Answers1

0

EDIT2 (after your addition that the actual problem wasn't the table view controller, as verified by your just recreating the project form scratch)

Ok, try replacing the following line

sideMenuViewController?.contentViewController = UINavigationController(rootViewController: (storyBoard.instantiateViewControllerWithIdentifier("MyTableViewController") as? MyTableViewController)!)

with

sideMenuViewController?.contentViewController = UINavigationController(rootViewController: (storyBoard.instantiateViewControllerWithIdentifier("MyTableViewController") as! UITableViewController))

You know that you MyTableViewController (btw, are you sure you shouldn't use the myTableViewController identifier here? Case-sensitivity..) is a subclass of UITableViewController, so you can use the forced conversion as! to cast it to it's parent, UITableViewController. The UINavigationController(rootViewController: ... takes a UIViewController as argument, so you need to cast to something Xcode can assess to be a UIViewController object.


EDIT (after your addition of part of the source code of the Main.storyboard)

From the storyboard nib you just posted, we see that your reuseIdentifier for your custom class is "MyTableViewCell" (reuseIdentifier="MyTableViewCell"), not myTableViewCell (case-sensitivity), where the latter is what you use int your table view controller when trying to access the cell. So preferably update your reuse identifier (via attributes inspector) to myTableViewCell.

Also, remove the line self.tableView.registerClass(MyTableViewCell.self, forCellReuseIdentifier: "myTableViewCell") from your viewDidLoad method; you don't need to explicitly register the class in this case (already made the connection to the custom cell class in your storyboard).


Note also that the myLabel in your custom table view cell class (MyTableViewCell) isn't an optional, so you shouldn't include the ? operator when accessing it.

Change the line cell.myLabel?.text = "22:40" to

cell.myLabel.text = "22:40"

If the above doesn't fix you error, have a look at my answer in this thread:

It describes in detail just a case like yours, so you should be able to the answer as a "tutorial" to go over your code, step by step.

Community
  • 1
  • 1
dfrib
  • 70,367
  • 12
  • 127
  • 192
  • The uppercase was a typo during question asking, now I've fixed it. I've also tried removing the `?` operator but nothing changed (same error). – lifeisfoo Dec 29 '15 at 12:31
  • I this is the case and you still get this error, I would try to rebuild (this very simple example) from scratch, and see if the error still persist. – dfrib Dec 29 '15 at 12:38
  • Also, try remove the `self.tableView.registerClass(MyTableViewCell.self, forCellReuseIdentifier: "myTableViewCell")` from your `viewDidLoad` method. You shouldn't need to register the class if you've already made the this custom cell-class connection in the storyboard. – dfrib Dec 29 '15 at 12:40
  • I've updated the question since I've discovered that with a new project everything works. Now I think that the problemi is the component that I'm using to have a side menu. – lifeisfoo Dec 29 '15 at 13:40
  • I finally solved this using [this answer](http://stackoverflow.com/a/20132836/3340702). Seems that was a xcode interface builder behaviour. I've also tried with your answer but nothing changed, it works in the same way also using `UITableViewController `. Thank you for your time. – lifeisfoo Dec 30 '15 at 08:32
  • Good to hear you solved it; many times those strange errors are connected to connections without reciever (hence the do-project-from-scratch tends to work). – dfrib Dec 30 '15 at 11:23