Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Personally I think that both suggested tutorials have a big flaw when it comes to <code>reuseIdentifier</code>. If you forget to assign it in interface builder or misspell it, you will load the nib each and every time <code>cellForRowAtIndexPath</code> gets called.</p> <p>Jeff LaMarche writes about this and how to fix it in this <a href="http://iphonedevelopment.blogspot.de/2010/04/table-view-cells-redux.html" rel="nofollow noreferrer">blog post</a>. Apart from <code>reuseIdentifier</code> he uses the same approach as in the apple documentation on <a href="https://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/TableView_iPhone/TableViewCells/TableViewCells.html" rel="nofollow noreferrer">Loading Custom Table-View Cells From Nib Files</a>. </p> <p>After having read all these articles I came up with following code:</p> <p><strong>Edit: If you are targeting iOS 5.0 and higher you'll want to stick with <a href="https://stackoverflow.com/a/11783706/782862">Duane Fields' answer</a></strong></p> <pre><code>@interface CustomCellWithXib : UITableViewCell + (NSString *)reuseIdentifier; - (id)initWithOwner:(id)owner; @end @implementation CustomCellWithXib + (UINib*)nib { // singleton implementation to get a UINib object static dispatch_once_t pred = 0; __strong static UINib* _sharedNibObject = nil; dispatch_once(&amp;pred, ^{ _sharedNibObject = [UINib nibWithNibName:NSStringFromClass([self class]) bundle:nil]; }); return _sharedNibObject; } - (NSString *)reuseIdentifier { return [[self class] reuseIdentifier]; } + (NSString *)reuseIdentifier { // return any identifier you like, in this case the class name return NSStringFromClass([self class]); } - (id)initWithOwner:(id)owner { return [[[[self class] nib] instantiateWithOwner:owner options:nil] objectAtIndex:0]; } @end </code></pre> <p>UINib (available in iOS 4.0 and later) is used here as a singleton, because although the <code>reuseIdentifier</code> is used, the cell still gets re-initialized about 10 times or so. Now <code>cellForRowAtIndexPath</code> looks like this:</p> <pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { CustomCellWithXib *cell = [tableView dequeueReusableCellWithIdentifier:[CustomCellWithXib reuseIdentifier]]; if (cell == nil) { cell = [[CustomCellWithXib alloc] initWithOwner:self]; } // do additional cell configuration return cell; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload