Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a reuse identifier has been registered with a UITableView already?

In iOS apps, we have to register nib files with our table view before we can use UITableView#dequeueReusableCellWithIdentifier.

Example:

static NSString *myReuseIdentifier = @"MyReuseIdentifier";
UINib *cellNib = [UINib nibWithNibName:myReuseIdentifier bundle:nil];
[self.tableView registerNib:cellNib forCellReuseIdentifier:myReuseIdentifier];

Is there a way to check if a Nib has already been registered with a UITableView?

I have a custom cell that I use in various tables across several controllers in my app. I'd like to move some of the code to a macro. Something like

-(CustomCell *)customCell:(UITableView *)tableView
{
    static NSString *reuseIdentifier = @"MyReuseIdentifier";
    if (![table hasAlreadyRegisteredNib:reuseIdentifier]){
       UINib *cellNib = [UINib nibWithNibName:reuseIdentifier bundle:nil];
       [self.tableView registerNib:cellNib forCellReuseIdentifier:reuseIdentifier];     
    }
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    return cell;
}
like image 634
bodacious Avatar asked Mar 22 '12 19:03

bodacious


People also ask

What is a reuse identifier?

The reuse identifier is associated with a UITableViewCell object that the table-view's delegate creates with the intent to reuse it as the basis (for performance reasons) for multiple rows of a table view. It is assigned to the cell object in initWithFrame:reuseIdentifier: and cannot be changed thereafter.

How can we use a reusable cell in UITableView?

For performance reasons, a table view's data source should generally reuse UITableViewCell objects when it assigns cells to rows in its tableView(_:cellForRowAt:) method. A table view maintains a queue or list of UITableViewCell objects that the data source has marked for reuse.

What is DequeueReusableCell?

DequeueReusableCell(NSString) Returns a reusable table view cell that was created with the given ReuseIdentifier. DequeueReusableCell(String) Returns a reusable table view cell that was created with the given ReuseIdentifier.

How do I register a cell with Swift?

Registering the cell To do that we register the XIB file in the view controller that has the UITableView . Then, open HabitsTableViewController. swift to finish registering the cell. Add the following line of code inside the viewDidLoad() method.


1 Answers

I am not sure if it that what you intend, but

-dequeueReusableCellWithIdentifier:

returns nil if the cell is not ready to reuse. Otherwise, it returns the cell, so you can simply try.

like image 148
Matthias Avatar answered Oct 08 '22 12:10

Matthias