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.