Why does dequeueReusableCellWithIdentifier cause my whole app to crash/hang? - ios

I've read all the relevant other questions on this topic and tried the fixes, none of which have worked. My app crashes/hangs to the extent that I have to force quit Xcode in order to restart working, when dequeueReusableCellWithIdentifier: is called.
It makes no difference if I use dequeueReusableCellWithIdentifier:, or dequeueReusableCellWithIdentifier:forIndexPath: , and I HAVE set the class with registerClass:forCellReuseIdentifier: , as you can see in the code below.
Registering the class in my ViewController:
#implementation LWSFlavourMatchesViewController
-(void)viewDidLoad
{
[super viewDidLoad];
_flavourMatchesView = [LWSFlavourMatchesView flavourMatchesViewWithDataSource:self.flavourMatchesDataSource andDelegate:self.flavourMatchesDelegate];
self.tableView = _flavourMatchesView;
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"flavourCell"];
}
And trying to dequeue cell in tableView:cellForRowAtIndexPath in my dataSource:
#implementation LWSFlavourMatchesDataSource
// other methods...
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *flavourCellIdentifier = #"flavourCell";
NSString *currentSelectedFlavour = [self.flavourWheel selectedFlavour];
UITableViewCell *tableViewCell = [tableView dequeueReusableCellWithIdentifier:flavourCellIdentifier forIndexPath:indexPath];
if(tableViewCell == nil)
{
tableViewCell = [[UITableViewCell alloc ]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:flavourCellIdentifier];
}
[tableViewCell.textLabel setText: currentSelectedFlavour];
return tableViewCell;
// return [UITableViewCell new];
}
If I remove all other code but un-comment out return [UITableViewCell new]; then the app does not crash. What is it about my dequeuing that is causing this problem?!

I refactored your tableview delegate. You do not need to check if the cell is nil because you registered the class with [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"flavourCell"];.
I made your cellIdentifier static. But to remove the duplication on the registerClass function may you make a #define REUSE_IDENTIFIER #"flavourCell".
If this is still slow, than is the [self.flavourWheel selectedFlavour]; the cause. Check out the instruments tutorial for performance improvements: http://www.raywenderlich.com/23037/how-to-use-instruments-in-xcode
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *flavourCellIdentifier = #"flavourCell";
NSString *currentSelectedFlavour = [self.flavourWheel selectedFlavour];
UITableViewCell *tableViewCell = [tableView dequeueReusableCellWithIdentifier:flavourCellIdentifier forIndexPath:indexPath];
[tableViewCell.textLabel setText: currentSelectedFlavour];
return tableViewCell;
}

try removing the class registration:
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"flavourCell"];
You shouldn't need to register the class if you are instantiating a generic UITableViewCell class cell from a storyboard

Another cause for this error can be-
invalid nib registered for identifier (Cell) - nib must contain exactly one top level object which must be a UICollectionReusableView instance
I had a UIView in my xib instead of a collectionViewCell. Of course, if you have multiple top level objects in the .xib, the same crash will show. Hope this helps.

Take care that if your cell is an object in a XIB, and you are using something like :
[self.tableView registerNib:[UINib nibWithNibName:#"cell_class_name" bundle:nil] forCellReuseIdentifier:#"cell_reuse_name"];
to register the cell, be sure the identifier in the attributes inspector in Interface Builder is correct, in this case #"cell_reuse_name".
If the identifier isn't the same, you may be stuck with an odd situation where creating new cells from the nib each time, i.e.
NSArray *objects = [bundle loadNibNamed:#"cell_nib_name"
owner:nil
options:nil];
cell = (UITableViewCell *)[objects safeObjectAtIndex:0];
seems to work fine, but trying to use
[tableView dequeueReusableCellWithIdentifier:#"cell_reuse_name"];
crashes.
In practice it's often easiest to use the same name for the XIB, custom class, and reuse identifier. Then if there are issues, you can just make sure they are all the same.

I had completely different issue. Mismatch between String/XIB based localization. It did help to enable/disable+remove unneeded localizations.
Try this:
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"NIB_NAME" owner:self options:nil];
If it hangs, there's something wrong with your XIB (like in my case).

Try this:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];
if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"flavourCellIdentifier"]; }

Related

Custom prototype cell in UIStoryboard is created but doesn't show up in UITableView

I have a project where I need to use a custom UITableViewCell. I'm designing the cell as a prototype in storyboard and it looks fine there. I assign the prototype to my custom UITableViewCell subclass, give it the same reuse identifier I'm using in my UITableView and link the UILabel on the prototype cell to an IBOutlet in my UITableViewCell subclass.
When I call it from the UITableView the cell is created and if I add labels and buttons in the code of that class (create them with a CGRect and all) they all work but the labels I've added in the storyboard never show up.
I don't understand how my subclass can be called and created successfully but its layout and subviews from the storyboard don't seem to exist as far as my app is concerned. What am I doing wrong?
Here's my cellForRowAtIndexPath code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath];
// Configure the cell...
return cell;
}
I've run into this issue before, and in my case, the problem was that the auto-generated code for the view controller included a call to:
[UITableView registerClass:forCellReuseIdentifier:]
I would suggest checking for and removing any calls to the above, or to
[UITableView registerNib:forCellReuseIdentifier:]
and trying your original code again.
acreichman, add casting in cellForRow and put an NSLog in you cell's awakeFromNib to see if you get there. Let me know...
Your cellForIndexViewPath should look like this, to create a simple custom cell with label,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SimpleTableCell";
SimpleTableCell *cell = (SimpleTableCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"SimpleTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.nameLabel.text = [tableData objectAtIndex:indexPath.row];
return cell;
}
Make sure that you have made all connections well, set datasource and delegate to table and then set the “Identifier” of the custom cell to "MyTableViewCell" in “Attributes Inspector” like this,
For storyboard:
Add "MyTableViewCell" instead of "SimpleTableCell" as shown in above screenshot.

List Songs in UITableViewController on iPhone? Works in Storyboard, NOT without it

I am NOT using Storyboards. I have a UITableViewController and I would like to display a list of songs from user's library.
This is my code so far:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
MPMediaQuery *songsQuery = [MPMediaQuery songsQuery];
NSArray *songs = [songsQuery items];
return [songs count];
}
But for this block, I do not know what to do. I found a tutorial for storyboards, but it is not valid here:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
MPMediaQuery *songsQuery = [MPMediaQuery songsQuery];
NSArray *songs = [songsQuery items];
MPMediaItem *rowItem = [songs objectAtIndex:indexPath.row];
cell.textLabel.text = [rowItem valueForProperty:MPMediaItemPropertyTitle];
cell.detailTextLabel.text = [rowItem valueForProperty:MPMediaItemPropertyArtist];
return cell;
}
This only works in Storyboard because I can click the cell in the storyboard and rename its identifier to 'Cell'. In the .xib/nib file in my project, all I see is a view filled with country's names. I cannot click a single cell, I can only edit the whole table.
My question is, what code must I put in - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath in order to display this list?
Thanks!
The basic problem you're encountering is that, when used in conjunction with a properly configured storyboard, dequeueReusableCell... will create a cell of the appropriate type if none is available to dequeue.
If you are using a standard UITableViewCell, you can use the following block to dequeue and/or create an appropriate cell:
static NSString* reuseIdentifier = #"Cell";
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
if(!cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
}
If, on the other hand, you're loading your cells from a nib file, you can just add:
[self.tableView registerNib:[UINib nibWithNibName:nibName bundle:[NSBundle mainBundle]] reuseIdentifier:reuseIdentifier];
to your viewDidLoad.
Alternatively you can use registerClass:forCellReuseIdentifier: if you have a custom cell class that sets up it's own subviews.
First off, check if the cell being dequeued is nil or not.
The next thing I can see a problem with is the fact that you aren't really loading anything in cellForRowAtIndexPath:. Basically what this method does is dequeue some cell which has been marked for reuse in an attempt to save memory, and if you haven't set the proper Restoration Identifier in the Interface Builder, then there is no way to know which Nib you want initialized to use here.
What used to happen (or at least my understanding of it) is that in cellForRowAtIndexPath: you would have to check if the cell returned from dequeueReusableCellWithIdentifier: was nil, and if so, you'd have to create the cell from scratch using something like this:
SomeCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell)
{
cell = [[[NSBundle mainBundle] loadNibNamed:#"SomeCellNib" owner:self options:nil] objectAtIndex:0];
}
and this would ensure that if no cell was dequeued that you would load up a fresh one from scratch, although I believe that Apple actually changed how dequeueReusableCellWithIdentifier: works, and as long as you've registered the Identifier, it will create a new cell for you.
For this reason I'm not sure what the problem is if you've set the Identifier properly, and all I can suggest is to try and manually load the cell.
EDIT: I forgot to mention where Restoration Identifiers can be set. The Restoration Identifer field is in the Identity tab, or the third tab in the Interface Builder:
To create a prototype cell inside a .nib, drag a UITableCellView out from the right sidebar. From there you can create your cell prototype, as well as set the cell reuse identifier.

Disappearing UITableViewCell on UITableView reloadRowsAtIndexPaths:

I have a few UITableViewCells that I am loading from an XIB file. Everything is great until I call the [UITableView reloadRowsAtIndexPaths:withRowAnimation:] method when the cell disappears. When I call [UITableView reloadData] everything loads find, when I scroll the cell on and off the view it will also reappear also. Weird.
I've also noticed that when I call [UITableView reloadRowsAtIndexPaths:withRowAnimation:] the UITableView will not try to reuse a cached cell and will try to get a new one with cell = [tableViewCells objectAtIndex:cellId];
Here is my code:
- (void)viewDidLoad
{
...
// the objects from the XIB files are loaded onto an NSArray instance variable at viewDidLoad
tableViewCells = [[NSBundle mainBundle] loadNibNamed:#"ProfileTableViewCell" owner:nil options:nil];
...
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
int cellId = /* some logic to get the correct cellID */
NSString *CellIdentifier = [NSString stringWithFormat:#"ProfileTableViewCell_%d", cellId];
ProfileTableViewCell *cell = (ProfileTableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell = [tableViewCells objectAtIndex:cellId];
// additional work to setup subviews for the cell
[cell prepareSubviews];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
}
and just in case here is some of the stuff I'm doing in [ProfileTableViewCell prepareSubviews]
- (void)prepareSubviews
{
...
[self.containerView.layer setCornerRadius:3];
[self.containerView.layer setBorderColor:UIColorFromRGB(0xCDCDCD).CGColor];
[self.containerView.layer setBorderWidth:2.0];
[self.containerView.layer setMasksToBounds:YES];
[self.containerView.layer setShouldRasterize:NO];
[self.containerView.layer setRasterizationScale:[UIScreen mainScreen].scale];
...
}
Thanks in advance to the awesome person that can help me out.
I'm not sure this is your problem, but the way you get your cells is not the normal way. You should make each type of cell in its own nib (with a unique identifier), and then register the nibs with registerNib:forCellReuseIdentifier:. In cellForRowAtIndexPath, just dequeue the cell you need based on the index path, and don't put anything in an if (cell == nil) clause, because that will not be invoked when you do it this way.
It seams that reloadRowsAtIndexPaths: doesn't work when you only need to change the height for a static cell.
Try to call just
[tableView beginUpdates];
[tableView endUpdates];
As the documentation says:
You can also use this method followed by the endUpdates method to
animate the change in the row heights without reloading the cell.

Using alloc and init when using a UITableViewCell from Storyboard

I'm doing a simples app using Storyboard that a have a View with a UITableView with a UITableViewCell that do the navigation to another UIView.
So a have to code to populate the cell on the table view.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"SampleCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
NSLog(#"cai no init da cell");
}
GPItem *item = [self.items objectAtIndex:indexPath.row];
cell.textLabel.text = #"Post";
cell.detailTextLabel.text = item.imageURL;
return cell;
}
I realised that the code if (cell == nil) { ... never executes so I really need to do that on uses the cell from Storyboard?
Thanks.
You are correct; that code is guaranteed to return a non-nil cell if you are using a storyboard. Also, in iOS 6, the new call dequeueReusableCellWithIdentifier:forIndexPath: never returns nil. See the discussion in my book:
http://www.apeth.com/iOSBook/ch21.html#_registering_a_cell_class
If you've declared your UITableViewCell in table view's prototype cells it's already allocated and just needs to be dequeued. If you're using a custom UITableViewCell subclass, then you must check if it's nil and allocate new entities when necessary.
Nope you don't need that code when using a cell made in your storyboard.
It is probably best to remove this code so that you crash nice and early if the identifier you gave to the cell in interface builder and the identifier you use in code ever drift. This snippet will mask this error and just provide a cell that you most likely was not intending to have.

Assertion failure in dequeueReusableCellWithIdentifier:forIndexPath:

So I was making an rss reader for my school and finished the code. I ran the test and it gave me that error. Here is the code it's referring to:
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell =
[tableView dequeueReusableCellWithIdentifier:CellIdentifier
forIndexPath:indexPath];
if (cell == nil) {
cell =
[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier];
}
here's the error in the output:
2012-10-04 20:13:05.356 Reader[4390:c07] * Assertion failure in
-[UITableView dequeueReusableCellWithIdentifier:forIndexPath:], /SourceCache/UIKit_Sim/UIKit-2372/UITableView.m:4460 2012-10-04
20:13:05.357 Reader[4390:c07] * Terminating app due to uncaught
exception 'NSInternalInconsistencyException', reason: 'unable to
dequeue a cell with identifier Cell - must register a nib or a class
for the identifier or connect a prototype cell in a storyboard'
* First throw call stack: (0x1c91012 0x10cee7e 0x1c90e78 0xb64f35 0xc7d14 0x39ff 0xd0f4b 0xd101f 0xb980b 0xca19b 0x6692d 0x10e26b0
0x228dfc0 0x228233c 0x228deaf 0x1058cd 0x4e1a6 0x4ccbf 0x4cbd9 0x4be34
0x4bc6e 0x4ca29 0x4f922 0xf9fec 0x46bc4 0x47311 0x2cf3 0x137b7 0x13da7
0x14fab 0x26315 0x2724b 0x18cf8 0x1becdf9 0x1becad0 0x1c06bf5
0x1c06962 0x1c37bb6 0x1c36f44 0x1c36e1b 0x147da 0x1665c 0x2a02 0x2935)
libc++abi.dylib: terminate called throwing an exception
and here's the code it shows in the error screen:
int main(int argc, char *argv[])
{
#autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
please help!
You're using the dequeueReusableCellWithIdentifier:forIndexPath: method. The documentation for that method says this:
Important: You must register a class or nib file using the registerNib:forCellReuseIdentifier: or registerClass:forCellReuseIdentifier: method before calling this method.
You didn't register a nib or a class for the reuse identifier "Cell".
Looking at your code, you seem to expect the dequeue method to return nil if it doesn't have a cell to give you. You need to use the dequeueReusableCellWithIdentifier: for that behavior:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
Notice that dequeueReusableCellWithIdentifier: and dequeueReusableCellWithIdentifier:forIndexPath: are different methods. See doc for the former and the latter.
If you want to understand why you'd want to ever use dequeueReusableCellWithIdentifier:forIndexPath:, check out this Q&A.
I think this error is about registering your nib or class for the identifier.
So that you may keep what you are doing in your tableView:cellForRowAtIndexPath function and just add code below into your viewDidLoad:
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"Cell"];
It's worked for me. Hope it may help.
Although this question is fairly old, there is another possibility:
If you are using Storyboards, you simply have to set the CellIdentifier in the Storyboard.
So if your CellIdentifier is "Cell", just set the "Identifier" property:
Make sure to clean your build after doing so. XCode sometimes has some issues with Storyboard updates
i had the same problem replacing with
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell==nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
solved
The problem is most likely because you config custom UITableViewCell in storyboard but you do not use storyboard to instantiate your UITableViewController which uses this UITableViewCell. For example, in MainStoryboard, you have a UITableViewController subclass called MyTableViewController and have a custom dynamic UITableViewCell called MyTableViewCell with identifier id "MyCell".
If you create your custom UITableViewController like this:
MyTableViewController *myTableViewController = [[MyTableViewController alloc] init];
It will not automatically register your custom tableviewcell for you. You have to manually register it.
But if you use storyboard to instantiate MyTableViewController, like this:
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"MainStoryboard" bundle:nil];
MyTableViewController *myTableViewController = [storyboard instantiateViewControllerWithIdentifier:#"MyTableViewController"];
Nice thing happens! UITableViewController will automatically register your custom tableview cell that you define in storyboard for you.
In your delegate method "cellForRowAtIndexPath", you can create you table view cell like this :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"MyCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
//Configure your cell here ...
return cell;
}
dequeueReusableCellWithIdentifier will automatically create new cell for you if there is not reusable cell available in the recycling queue.
Then you are done!
I'll just add that Xcode 4.5 includes the new dequeueReusableCellWithIdentifier:forIndexPath:
in its default template code - a potential gotcha for developers expecting the older dequeueReusableCellWithIdentifier: method.
Swift 2.0 solution:
You need to go into your Attribute Inspector and add a name for your cells Identifier:
Then you need to make your identifier match with your dequeue like this:
let cell2 = tableView.dequeueReusableCellWithIdentifier("ButtonCell", forIndexPath: indexPath) as! ButtonCell
Alternatively
If you're working with a nib you may need to register your class in your cellForRowAtIndexPath:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "SwitchCell")
// included for context
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchCell", forIndexPath:indexPath) as! SwitchCell
//... continue
}
Apples's UITableView Class Reference says:
Prior to dequeueing any cells, call this method or the
registerNib:forCellReuseIdentifier: method to tell the table view how
to create new cells. If a cell of the specified type is not currently
in a reuse queue, the table view uses the provided information to
create a new cell object automatically.
If you previously registered a class or nib file with the same reuse
identifier, the class you specify in the cellClass parameter replaces
the old entry. You may specify nil for cellClass if you want to
unregister the class from the specified reuse identifier.
Here's the code from Apples Swift 2.0 framework:
// Beginning in iOS 6, clients can register a nib or class for each cell.
// If all reuse identifiers are registered, use the newer -dequeueReusableCellWithIdentifier:forIndexPath: to guarantee that a cell instance is returned.
// Instances returned from the new dequeue method will also be properly sized when they are returned.
#available(iOS 5.0, *)
func registerNib(nib: UINib?, forCellReuseIdentifier identifier: String)
#available(iOS 6.0, *)
func registerClass(cellClass: AnyClass?, forCellReuseIdentifier identifier: String)
In your storyboard you should set the 'Identifier' of your prototype cell to be the same as your CellReuseIdentifier "Cell". Then you won't get that message or need to call that registerClass: function.
If you are going with Custom Static Cells just comment this method:
//- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
// static NSString *CellIdentifier = #"notificationCell";
// UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// return cell;
//}
and give the cells an identifier at "Attributes Inspector" in storyboard.
I give you the answer in both Objective C and Swift.Before that I want to say
If we use the dequeueReusableCellWithIdentifier:forIndexPath:,we must register a class or nib file using the registerNib:forCellReuseIdentifier: or registerClass:forCellReuseIdentifier: method before calling this method as
Apple Documnetation Says
So we add registerNib:forCellReuseIdentifier: or registerClass:forCellReuseIdentifier:
Once we registered a class for the specified identifier and a new cell must be created, this method initializes the cell by calling its initWithStyle:reuseIdentifier: method. For nib-based cells, this method loads the cell object from the provided nib file. If an existing cell was available for reuse, this method calls the cell’s prepareForReuse method instead.
in viewDidLoad method we should register the cell
Objective C
OPTION 1:
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"cell"];
OPTION 2:
[self.tableView registerNib:[UINib nibWithNibName:#"CustomCell" bundle:nil] forCellReuseIdentifier:#"cell"];
in above code nibWithNibName:#"CustomCell" give your nib name instead of my nib name CustomCell
SWIFT
OPTION 1:
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
OPTION 2:
tableView.registerNib(UINib(nibName: "NameInput", bundle: nil), forCellReuseIdentifier: "Cell")
in above code nibName:"NameInput" give your nib name
Working with Swift 3.0:
override func viewDidLoad() {
super.viewDidLoad()
self.myList.register(UINib(nibName: "MyTableViewCell", bundle: nil), forCellReuseIdentifier: "Cell")
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = myList.dequeueReusableCell(withIdentifier: "Cell", for: indexPath as IndexPath) as! MyTableViewCell
return cell
}
I spent hours last night working out why my programmatically generated table crashed on [myTable setDataSource:self]; It was OK commenting out and popping up an empty table, but crashed every time I tried to reach the datasource;
I had the delegation set up in the h file: #interface myViewController : UIViewController
I had the data source code in my implementation and still BOOM!, crash every time! THANK YOU to "xxd" (nr 9): adding that line of code solved it for me! In fact I am launching a table from a IBAction button, so here is my full code:
- (IBAction)tapButton:(id)sender {
UIViewController* popoverContent = [[UIViewController alloc]init];
UIView* popoverView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 300)];
popoverView.backgroundColor = [UIColor greenColor];
popoverContent.view = popoverView;
//Add the table
UITableView *table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 200, 300) style:UITableViewStylePlain];
// NEXT THE LINE THAT SAVED MY SANITY Without it the program built OK, but crashed when tapping the button!
[table registerClass:[UITableViewCell class] forCellReuseIdentifier:#"Cell"];
table.delegate=self;
[table setDataSource:self];
[popoverView addSubview:table];
popoverContent.contentSizeForViewInPopover =
CGSizeMake(200, 300);
//create a popover controller
popoverController3 = [[UIPopoverController alloc]
initWithContentViewController:popoverContent];
CGRect popRect = CGRectMake(self.tapButton.frame.origin.x,
self.tapButton.frame.origin.y,
self.tapButton.frame.size.width,
self.tapButton.frame.size.height);
[popoverController3 presentPopoverFromRect:popRect inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}
#Table view data source in same m file
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSLog(#"Sections in table");
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"Rows in table");
// Return the number of rows in the section.
return myArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
NSString *myValue;
//This is just some test array I created:
myValue=[myArray objectAtIndex:indexPath.row];
cell.textLabel.text=myValue;
UIFont *myFont = [ UIFont fontWithName: #"Arial" size: 12.0 ];
cell.textLabel.font = myFont;
return cell;
}
By the way: the button must be linked up with as an IBAction and as a IBOutlet if you want to anchor the popover to it.
UIPopoverController *popoverController3 is declared in the H file directly after #interface between {}
FWIW, I got this same error when I forgot to set the cell identifier in the storyboard. If this is your issue then in the storyboard click the table view cell and set the cell identifier in the attributes editor. Make sure the cell identifier you set here is the same as
static NSString *CellIdentifier = #"YourCellIdenifier";
I had the same issue, was having the same error and for me it worked like this:
[self.tableView registerNib:[UINib nibWithNibName:CELL_NIB_HERE bundle: nil] forCellReuseIdentifier:CELL_IDENTIFIER_HERE];
Maybe it will be usefull for someone else.
I setup everything correctly in the Storyboard and did a clean build but kept getting the error " must register a nib or a class for the identifier or connect a prototype cell in a storyboard"
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"Cell"];
Corrected the error but i'm still at a loss. I'm not using a 'custom cell', just a view with a tableview embeded. I have declared the viewcontroller as delegate and datasource and made sure the cell identifier matches in file. whats going on here?
This might seem stupid to some people but it got me. I was getting this error and the problem for me was that I was trying to use static cells but then dynamically add more stuff. If you are calling this method your cells need to be dynamic prototypes. Select the cell in storyboard and under the Attributes inspector, the very first thing says 'Content' and you should select dynamic prototypes not static.
Just a supplement of the answers:
There may be a time you set all things right, but you may accidentally add some other UIs in you .xib, like a UIButton:
Just delete the extra UI, it works.
Make sure that the CellIdentifier == identifier of the cell in a storyboard, both names are same. Hope this works for u
In my case, the crash happened when I calleddeselectRowAtIndexPath:
The line was [tableView deselectRowAtIndexPath:indexPath animated:YES];
Changing it to [self.tableView deselectRowAtIndexPath:indexPath animated:YES]; FIXED MY PROBLEM!
Hope this helps anyone
In Swift this problem can be solved by adding the following code in your
viewDidLoad
method.
tableView.registerClass(UITableViewCell.classForKeyedArchiver(), forCellReuseIdentifier: "your_reuse_identifier")
you have to be aware that when using interface builder and creating a Xib (nib) containing one cell that there is also a placeholder created that points to the class that will be used. Meaning, when you place two UITableViewCell in one Xib file you possibly run into the exact same trouble causing an *** Assertion failure .... The placeholder mechanism doesn't work adn will be confused then. Instead placing different placeholders in one Xib read on..
The most easy solution (even if that seems a bit to simple) is to place one Cell at a time in one Xib. IB will create a placeholder for you and all works as expected then. But this then leads directly to one extra line of code, because then you need to load the correct nib/xib asking for the reuseIdentified Cell where it resides in.
So the following example code focuses the use of multiple Cell Indentifiers in one tableview where an Assertion Failure is very common.
// possibly above class implementation
static NSString *firstCellIdentifier = #"firstCellIdentifier";
static NSString *secondCellIdentifier = #"secondCellIdentifier";
// possibly in -(instancetype)init
UINib *firstNib = [UINib nibWithNibName:#"FirstCell" bundle:nil];
[self.tableView registerNib:firstNib forCellReuseIdentifier:firstCellIdentifier];
UINib *secondNib = [UINib nibWithNibName:#"SecondCell" bundle:nil];
[self.tableView registerNib:secondNib forCellReuseIdentifier:secondCellIdentifier];
Another trouble with the use of two CellIdentifier's in one UITableView is that row height and/or section height have to be taken care of. Two cells can have different heights of course.
When registering classes for reuse the code should look different.
The "simple solution" looks also much different when your cells reside inside a Storyboard instead of Xib's. Watch out for the placeholders.
Keep also in mind that interface builder files have version wise variations and need to be set to a version that your targeted OS version supports. Even if you may be lucky that the particular feature you placed in your Xib is not changed since the last IB version and does not throw errors yet. So a Xib made with IB set to be compatible to iOS 13+ but used in a target that is compiled on an earlier version iOS 12.4 will cause also trouble and can end up with Assertion failure.
Ran into this error bc cell re-use identifier was wrong-- a rookie mistake but it happens:
1. Makes SURE cell re-use idenifier has no misspellings or missing letters.
2. Along same line, don't forget capitalization counts.
3. Zeroes are not "O"s (Ohs)

Resources