Instruments shows leak when dequeuing Custom table view cells in cellForRowAtIndexPath - ios

I am getting a memory leak in Instruments related to the table view delegate method cellForRowAtIndexPath when using custom table view cells. I am using XCode 5 but ARC is disabled. I have created my custom table view cell as a separate xib and I load that xib in my viewDidLoad method using nibWithNibName (which, if i remember, checks whether you have a cell or not so you dont have to check if cell != nil in the delegate method). Below are the sections of code that are relevant:
static NSString *const TransactionResultCellIdentifier =
#"TransactionResultCell";
- (void)viewDidLoad
{
[super viewDidLoad];
UINib *cellNib = [UINib nibWithNibName:TransactionResultCellIdentifier bundle:nil];
[self.transactionsTableView registerNib:cellNib forCellReuseIdentifier:TransactionResultCellIdentifier];
cellNib = [UINib nibWithNibName:LoadingCellIdentifier bundle:nil];
[self.transactionsTableView registerNib:cellNib forCellReuseIdentifier:LoadingCellIdentifier];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
TransactionResultCell *cell = (TransactionResultCell *)[tableView dequeueReusableCellWithIdentifier:TransactionResultCellIdentifier];
if(self.isLoading){
return [tableView dequeueReusableCellWithIdentifier:LoadingCellIdentifier];
}
else{
TransactionResult *transactionResult = [self.transactionResults objectAtIndex:indexPath.row];
cell.transactionDescriptionLabel.text = [NSString stringWithFormat:#"%#: %#", transactionResult.transactionID, transactionResult.transactionDescription];
cell.transactionPriceLabel.text = [#"Price: $" stringByAppendingString:transactionResult.transactionPrice];
self.totalPrice += [transactionResult.transactionPrice doubleValue];
}
return cell;
}
Instruments points me to the line up above where i am attempting to dequeue the custom table view cell along with obvious UILabel leaks that are part of the xib structure that i custom built in IB.
Can anyone point me to a solution here? Thanks...

The problem could be that first line in tableView:cellForRowAtIndexPath:. You create a TransactionResultCell that you don't do anything with if self.isLoading evaluates to true. That line should be inside the else clause (as well as the return cell line).

On viewWillDisappear:animated, call to nil out your nibs.
[self.tableView registerNib:nil forCellReuseIdentifier:[WIActivityNameLabelCell reuseIdentifier]];
I have 5 custom nibs in my view, and I was losing about 0.2mb per load, which added up. I suspect it is because I keep my nib and reuseIds in the actual custom table view cell, calling them as class methods. I think this was creating some kind of strong reference that was leaking. Anyway, nilling the nib solved it. Note that the apple documentation states:
If you previously registered a class or nib file with the same reuse identifier, the nib you specify in the nib parameter replaces the old entry. You may specify nil for nib if you want to unregister the nib from the specified reuse identifier.

Related

Declaring array error in swift2 [duplicate]

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)

dequeueReusableCellWithIdentifier always returns nil

I have a static table with 6 cells and a couple sections. When I initialize a cell it always returns nil, although I have used this exact same method in the passed...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == SAVE_SECTION) {
ATSaveCell *cell = [tableView dequeueReusableCellWithIdentifier:#"SaveCell"];
if(cell == nil) {
NSLog(#"nil cell");
cell = [[ATSaveCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"SaveCell"];
}
cell.textLabel.text = #"test";
return cell;
}
nil cell is always outputted. In my storyboard, I have a tableviewcontroller that has the cell defined and the id is "SaveCell". I have also checked to make sure the table ciew controller is the same class as the class I am working in... I have used this exact same method in the passed, so I am not sure why the cells are returning nil everytime.
Also, to initialize my tableviewcontroller:
ATSearchSettingsViewController *mySearchSettings = [sb instantiateViewControllerWithIdentifier:#"SearchSettings"];
It's pretty clear that the table view is not registering the prototype cells in the storyboard.
If the problem is the UITableView is not dequeuing a cell from a storyboard. Try checking that you are using prototype cells instead of static cells. The UITableView will not dequeue a static cell.
If the problem is that you are always calling [[ATSaveCell alloc] init]. The table view will need to if it doesn't have anything the reuse.
From the docs: dequeueReusableCellWithIdentifier
This method dequeues an existing cell if one is available or creates a
new one using the class or nib file you previously registered. If no
cell is available for reuse and you did not register a class or nib
file, this method returns nil.
Therefore, if there are not enough cells to fit the view, it will always create a new one.

iOS: DequeTableViewCell..a little bit confused

I want to alter the font size and color etc. for my UITableView cells. I've designed the cells custom in Xcode and got everything working.
First of I'll post my code here:
UITableViewController:
- (void)viewDidLoad
{
[super viewDidLoad];
[self.tableView registerClass:MainCategoryTableViewCell.class forCellReuseIdentifier:#"MainCategoryCell"];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"MainCategoryCell";
MainCategoryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
return cell;
}
And my custom cell:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
self.title.font = [Theme tableCellTitleFont];
self.title.textColor = [Theme tableCellTitleColor];
self.subcategories.font = [Theme tableCellSubTitleFont];
self.subcategories.textColor = [Theme tableCellSubTitleColor];
self.costs.font = [Theme tableCellValueFont];
self.costs.textColor = [Theme tableCellValueColor];
}
return self;
}
I'm confused now how this dequeue works:
As far as I understood if I register the class in the viewDidLoad, the initWithStyle method of the cell gets ONLY called, when theres no cell for reuse. If theres a cell for reuse it will be used. I've seen a lot of if(cell == nil) calls in other code snippets but is that really necessary? I thought the registerClass method takes care of that anyway?
And at the moment my cells will be displayed completely empty. Before I registered the class everything worked, however the initWithStyle didn't get called..
Complete cellForRowAtIndexPathMethod:
#pragma mark Delegate methods
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"MainCategoryCell";
MainCategoryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
MainCategory *mainCategory = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.title.text = mainCategory.name;
cell.subcategories.text = [NSString stringWithFormat:#"%i subcategories", [[mainCategory getNumberOfSpendingCategories] integerValue]];
cell.costs.text = [[mainCategory getMonthlyCostsOfAllSpendingCategories] getLocalizedCurrencyString];
if(!mainCategory.icon){
cell.icon.image = [UIImage imageNamed:#"DefaultIcon.png"];
} else {
cell.icon.image = [UIImage imageNamed:mainCategory.icon];
}
if(!mainCategory.color){
cell.backgroundColor = [PresetColor colorForPresetColor:PresetColorsWhite];
} else {
cell.backgroundColor = [PresetColor colorForPresetColor:(PresetColors)[mainCategory.color intValue]];
}
cell.cellBackground.image = [[UIImage imageNamed:#"content-bkg"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
return cell;
}
If you have defined the cell as "prototype cell" for the table view in the xib/storyboard file, then you don't have to register it at all. If the custom cell is in a separate nib file, you register the custom cell with registerNib, not registerClass. For example:
[self.tableView registerNib:[UINib nibWithNibName:#"MainCategoryTableViewCell" bundle:nil]
forCellReuseIdentifier:#"MainCategoryCell"];
For cells instantiated from a nib file, initWithCoder is called, not initWithStyle.
To configure any outlets of your custom cell, override awakeFromNib. The connections are
not yet established in initWithCoder.
For best understanding see the below image for just a deque reference.
Deque means you can add and delete cells from both the ends.
By ends I mean up and down.
Lets say you have 4 cell containg Acell,Bcell,Ccell and Dcell and height for row is for three cells.
so at a time only 3 cells would be visible.
when you scroll to see the Dcell , Acell would become as invisible row and memory for it will be reused for Dcell.
In the same way when you scroll to see the Acell , Dcell would become as invisible row and memory for it will be reused for Acell.
It says clearly in documentation
dequeueReusableCellWithIdentifier:forIndexPath:
For performance reasons, a table view's data source should generally
reuse UITableViewCell objects when it assigns cells to rows in its
tableView:cellForRowAtIndexPath: method. A table view maintains a
queue or list of UITableViewCell objects that the data source has
marked for reuse. Call this method from your data source object when
asked to provide a new cell for the table view. This method dequeues
an existing cell if one is available or creates a new one based on the
class or nib file you previously registered.
.
dequeueReusableCellWithIdentifier:
Return Value : A UITableViewCell object with the associated identifier
or nil if no such object exists in the reusable-cell queue.
Discussion : For performance reasons, a table view's data source
should generally reuse UITableViewCell objects when it assigns cells
to rows in its tableView:cellForRowAtIndexPath: method. A table view
maintains a queue or list of UITableViewCell objects that the data
source has marked for reuse. Call this method from your data source
object when asked to provide a new cell for the table view. This
method dequeues an existing cell if one is available or creates a new
one using the class or nib file you previously registered. If no cell
is available for reuse and you did not register a class or nib file,
this method returns nil.
If you 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.
Before introducing storyboard.The tableview checks the returned cell which can be nil .So if nil we must reallocate the cell and tehn initialize and provide the cell in the datasource method

How to assign File's Owner when using UITableView registerNib: to load a custom UITableViewCell from nib?

So i've been looking at using UITableView's registerNib: and [dequeueReusableCellWithIdentifier: forIndexPath:] for loading up a custom UITableCellView from a NIB. Here are the important bits from my controller:
- (void)viewDidLoad
[super viewDidLoad];
self.tableView.bounces = NO;
[self.tableView registerNib:[UINib nibWithNibName:#"ProgramListViewCell" bundle:nil] forCellReuseIdentifier:#"Cell"];
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
TVProgramListTableViewCell *cell = (TVProgramListTableViewCell *)[tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
cell.frame = CGRectMake(0, 0, CELLWIDTH, OPENCELLHEIGHT);
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.clipsToBounds = YES;
cell.titleLabel.text = [NSString stringWithFormat:#"herpa derp: %i", indexPath.row];
return cell;
So i'm registering the NIB when the view loads and then utilizing it for cell dequeuing. Up to this point everything is working like i expect it to. My custom TVProgramListTableViewCell is being properly loaded from the NIB and it's IBOutlet is being wired up.
The NIB contains a view with a button in it that i would like to have fire events to the controller. I can set the File's Owner type as my Table View Controller class but i do not know how to actually wire up the File's Owner.
Now if i was using loadNibNamed:, and loading the NIB myself, wiring up the File's Owner would be easy. Is there any way to achieve this while utilizing registerNib? Other than not being able to wire up the File's Owner this seems like the perfect way of using custom cells in a UITableView.
As far as I know, there's no way to set the file's owner to your table view controller and connect up an action method to a button in a xib file -- I've tried that, and it crashes the app. The way this is normally done is to call addTarget:action:forControlEvents: on your button in the cellForRowAtIndexPath method, and pass self as the target.

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