Skip to content

Instantly share code, notes, and snippets.

@jtbandes
Created June 7, 2010 22:02
Show Gist options
  • Save jtbandes/429252 to your computer and use it in GitHub Desktop.
Save jtbandes/429252 to your computer and use it in GitHub Desktop.
// replace annoying boilerplate with declarative justice using FunctionalKit:
UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
// =>
// nota bene: category on UITableView for convenient factory method is highly recommended.
id maybeCell = [[aTableView maybe] dequeueReusableCellWithIdentifier:CellIdentifier];
UITableViewCell *cell = [maybeCell orJustFromBlock:^{ return [UITableViewCell cellWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; }];
@jonsterling
Copy link

Excellent idea, although a more illustrative example might look like

UITableViewCell *cell = [maybeCell orJustFromBlock:^{
  id c = [UITableViewCell cellWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
  [c setBackgroundColor:[UIColor redColor]];
  [c setTextColor:[UIColor greenColor]];
  return c;
}];

If extra configuration is needed in the initial creation of the UITableViewCell object, your block construct could prove very useful!

@jtbandes
Copy link
Author

jtbandes commented Jun 7, 2010

That's a good example. However, I added the block even with no configuration for a good reason: if you use your original code, you'll be creating extra cells whether or not they're needed.

@jonsterling
Copy link

Zomg, good point. Damn Objective-C not being a lazy-evaluating language!

@jonsterling
Copy link

I need to make a HOM for forcing operations to be lazy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment