objective-c变量初始化中的奇怪语法

时间:2015-02-09 15:14:17

标签: objective-c syntax

我刚刚在SO回答中看到了这个语法,这个叫做什么,以及Objective-C文档中的定义是什么?

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

我以前从未见过这个,或者至少没有注意到它,它似乎是一个匿名函数。通常块具有^

2 个答案:

答案 0 :(得分:2)

这是gcc extension - ({ ... })块中评估的最后一件事成为表达式的结果(本例中为view)。它最常用于类似函数的宏。

答案 1 :(得分:1)

它被称为statement expression and is gcc extension to C。它的目的是确定范围。一旦分配了变量,它就完全配置好了。


顺便说一句:

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

在此示例中,属性必须为strong才能生效。但是对于观点并不理想,因为超级观点强有力。

您应该标记属性weak并执行此操作:

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

或者你可以使用隐式声明的块

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

[self.view addSubview:backgroundView];
self.backgroundView = backgroundView;