10

I was perusing the code of the third-party RESideMenu framework, and noticed some strange syntax that seemed to work just fine. Here is the confusing bit:

self.tableView = ({
    UITableView *tableView = [[UITableView alloc] initWithFrame:frame style:UITableViewStylePlain];
    tableView.autoresizingMask = mask;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.opaque = NO;
    tableView.backgroundColor = [UIColor clearColor];
    tableView.backgroundView = nil;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.bounces = NO;
    tableView.scrollsToTop = NO;
    tableView;
});

How does this syntax work? I suspect it has something to do with a C-level block scoping, but I have never seen this before. I also considered it may be a new feature with Objc-2.0 literals, but I don't think that is true.

So I guess my question is how does this work/what makes this work?

jscs
  • 63,694
  • 13
  • 151
  • 195
anon_dev1234
  • 2,143
  • 1
  • 17
  • 33
  • http://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html#Statement-Exprs – matt Feb 25 '14 at 18:36
  • BTW I had the same question; you might like to look at this thread: http://lists.apple.com/archives/xcode-users/2013/Aug/msg00027.html – matt Feb 25 '14 at 18:43
  • In the end I decided not to use it in my own code. But note that you can get a similar effect with curly braces alone, if all you want to do is confine the scope of a temporary variable declaration. – matt Feb 25 '14 at 18:44
  • Interesting to know, thanks for the information! I have been searching for quite some time - I like that it logically separates the initialization code, makes it look cleaner in my opinion :) – anon_dev1234 Feb 25 '14 at 18:52
  • 1
    One more consideration: I don't trust these GCC extensions. I relied on this one for years: http://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html#Nested-Functions Then Apple withdrew it and all my code broke. So I said Never Again! – matt Feb 25 '14 at 18:55
  • Good point. I suppose it's better to future-proof the code at the cost of syntactic sugar at that point. Thanks for all the insight! – anon_dev1234 Feb 25 '14 at 19:00
  • @bgoers - To see this feature in use look at the standard macro `MAX` (& friends) in Xcode (and probably other compilers). It's a good way to make macros behave the same as functions - only evaluate their arguments once. – CRD Feb 25 '14 at 19:47

1 Answers1

10

As mentioned on NSHipster:

Behind the magic is a GCC C extension, which causes a code block to return a value if enclosed within brackets and parentheses.

This not only segregates configuration details into initialization, but the additional scope allows generic variable names like frame, button, and view to be reused in subsequent initializations. No more loginButtonFrame = ... / signupButtonFrame = ...!

Community
  • 1
  • 1
Gavin
  • 8,204
  • 3
  • 32
  • 42