简体   繁体   中英

Nil outlets with tableview dequeueReusableCellWithIdentifier

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM