1

I just saw this syntax in a SO answer, what is this called, and where in the Objective-C documentation is it defined?

self.backgroundView = (
{
    UIView * view = [[UIView alloc] initWithFrame:self.bounds];
    view.backgroundColor = [UIColor whiteColor];
    view;
});

I've never seen this before, or at least not noticed it, it seems to be an anonymous function. Normally blocks have a ^

ahwulf
  • 2,584
  • 15
  • 29

2 Answers2

2

It's a gcc extension - the last thing evaluated in the ({ ... }) block becomes the result of the expression (view in this example). It's most commonly used for function-like macros.

Paul R
  • 208,748
  • 37
  • 389
  • 560
1

it is called statement expression and is gcc extension to C. It purpose is scoping. as soon as the variable is assigned, it is fully configured.


BTW:

self.backgroundView = (
{
    UIView * view = [[UIView alloc] initWithFrame:self.bounds];
    view.backgroundColor = [UIColor whiteColor];
    view;
});

in this example the property must be strong to work. but is not ideal for views, as the super view is holding it strong.

You should mark the property weak and do this:

UIView *backgroundView = (
{
    UIView * view = [[UIView alloc] initWithFrame:self.bounds];
    view.backgroundColor = [UIColor whiteColor];
    view;
});
[self.view addSubview:backgroundView];
self.backgroundView = backgroundView;

alternatively you can use implicitly declared blocks

UIView *backgroundView = ^{
    UIView * view = [[UIView alloc] initWithFrame:self.bounds];
    view.backgroundColor = [UIColor whiteColor];
    return view;
}();

[self.view addSubview:backgroundView];
self.backgroundView = backgroundView;
vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
  • BTW the class in my trying this out is a UITableViewHeaderFooterView, the property is already defined. – ahwulf Feb 09 '15 at 15:27