Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment of several statements enclosed in parentheses and curly braces in ObjC [duplicate]

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?

like image 557
anon_dev1234 Avatar asked Feb 25 '14 18:02

anon_dev1234


1 Answers

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 = ...!

like image 116
Gavin Avatar answered Oct 14 '22 09:10

Gavin