Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reason for dispatch_once in heightForImageCellAtIndexPath

When I search for how to implement auto sizing cell in iOS I come across many examples (here here and here) with this mysterious code in - (CGFloat)heightForImageCellAtIndexPath:(NSIndexPath *)indexPath

static CommentedItemCell *sizingCell = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    sizingCell = [self.tableView dequeueReusableCellWithIdentifier:kCellIdentifier];
});

But I can't find a reason behind this dispatch_once thing. I think its aim to save some memory, but why this style. Why not define property and lazy load it.

@property (nonatomic, strong) UITableViewCell sizingCell;

with

- (UITableViewCell)getSizingCell
{
  if (_sizingCell) return _sizingCell;

  _sizingCell = [self.tableView dequeueReusableCellWithIdentifier:kCellIdentifier];

  return _sizingCell;
}

Want to know its just coding style or there is some benefit behind this dispatch_once implementation.

like image 732
sarunw Avatar asked Apr 03 '15 08:04

sarunw


2 Answers

The behavior of dispatch_once is in the name. It does something once and only once.

The benefit of dispatch_once() over the other approach is that it's faster. It's also semantically cleaner, because the entire idea of dispatch_once() is "perform something once and only once", which is precisely what we're doing.

It's a low level GCD API, which provides performance improvements over any other approach.

like image 126
Sanjay Mohnani Avatar answered Oct 02 '22 16:10

Sanjay Mohnani


It will only save memory if you have multiple instances of your table / collection view because they will all reuse the same instance. This is more efficient, though likely not often used. Using the static also keeps all the code in one place.

You certainly can do it the way you propose, and the benefits of the dispatch once aren't huge, but I'd choose the dispatch once route (though you could use dispatch once in your model to achieve th lazy load).

like image 24
Wain Avatar answered Oct 02 '22 16:10

Wain