3

More or less by accident I stumbled upon this form of scoping

DataSource *dataSource =({
    NSInteger idx = [[self.tableView indexPathForSelectedRow] row];
    DataSource *dataSource = [DataSource new];
    dataSource.address = self.destinations[idx][0];
    dataSource.name    = self.destinations[idx][1];
    dataSource;
});

I think it is a nice way to create and instantiate objects and variables as temporary variables will only live as long as they are needed to create the object I really need and care for. In the code above idx will be gone as soon as I write the inner dataSource to the outer dataSource, as the scope will be left soon after.
Also I find the fact appealing that a fully instantiated and configured object will be set to the outer object.
Actually I don't even know if this is a C or Objective-C feature or a syntax candy added to clang.


@Unheilig
this is a syntax for organizing code. it is not something like a block or closure. at the end of the code you just have a fully instantiated and configured object.

This comes in handy if you need an object only to pass it as an argument to a method, but the configuration of that object takes more than one statement. Instead of assigning it to a local temporary variable you can pass in a statement expression.

[[MYViewController alloc] initWithDataSource:({
    NSInteger idx = [[self.tableView indexPathForSelectedRow] row];
    DataSource *dataSource = [DataSource new];
    dataSource.address = self.destinations[idx][@"address"];
    dataSource.name    = self.destinations[idx][@"name"];
    dataSource;
})];

In a non-ARC environment you could even call autorelease inside the expression statement.

So it is just about code organization and a lot of personal taste I guess.

beatgammit
  • 19,817
  • 19
  • 86
  • 129
vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
  • I hope it has worked well for you so far. Could you cite a scenario where this might be useful? How would you call / invoke it? Thanks in advance. – Unheilig Jan 13 '14 at 02:54

1 Answers1

9

It is a GCC extension, called "statement expression", described at http://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html.

devnull
  • 118,548
  • 33
  • 236
  • 227
Gwendal Roué
  • 3,949
  • 15
  • 34
  • 1
    You should really add the pertinent parts of that url into your answer in case the link ever becomes broken. – Code Maverick Feb 05 '14 at 21:55
  • @CodeMaverick: The answer is sufficient IMO. I ask for the name, Gwendal gave it. additionally he tells that it is a GCC extension. It is an perfect answer. – vikingosegundo Feb 13 '14 at 12:35