0

I have a XIB to design a UITableViewCell.

I always register the XIB and then dequeue cells using a reuse-identifier, as is common. Does setting Attributes Inspector > Table View Cell > Identifier have any purpose when using a XIB?

meaning-matters
  • 21,929
  • 10
  • 82
  • 142
  • You do not need a cell identifier if you design in a xib. You only need it if you design in the storyboard. – matt Oct 06 '18 at 15:31
  • I don’t even know what you mean. There isn’t even a place in a xib to enter a cell reuse identifier. It just isn’t needed. – matt Oct 06 '18 at 15:35
  • Oh yeah. But leave it blank. It is not used if you register the cell in a separate nib. – matt Oct 06 '18 at 15:39
  • The correct method isn't "not so nice"; it's great. If there were no reuse identifier in code, the runtime wouldn't know what xib to load! Registration identifies the xib with the reuse identifier. It's brilliant. – matt Oct 06 '18 at 15:54
  • Perhaps the problem is that you don't know what the correct architecture is? Added that to my answer. – matt Oct 06 '18 at 15:57
  • I'm explaining that if the code didn't know the reuse identifier beforehand it couldn't find the nib in the first place. – matt Oct 06 '18 at 16:00

1 Answers1

1

There’s no way for code to read the settings inside a nib. If you design the cell in the storyboard as a prototype cell, you yourself have to write identically the reuse identifier in the nib and the reuse identifier in your code, and that’s that.

If you don’t like that, register a separate nib for the cell instead of getting the cell prototype from the storyboard. That’s the architecture I prefer in any case. You just make the reuse identifier a constant in your code, in one place, and you’re all set. You do not need to specify the reuse identifier in the nib.

The correct typical architecture for getting your cells from a separate nib looks like this:

class RootViewController : UITableViewController {
    let cellID = "Cell"
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.register(UINib(nibName:"MyCell", bundle:nil),    
            forCellReuseIdentifier: self.cellID) // *
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: self.cellID, 
            for: indexPath) as! MyCell
        // ...
    }
}

The reuse id in the nib is completely irrelevant.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • It wouldn't be "nice". It would mean going backwards in time! First you register using the reuse identifier. Then the runtime locates the nib and loads it. How can you know the reuse identifier from the nib before loading the nib? If you could do that, the universe would explode. That would be bad. – matt Oct 06 '18 at 16:42