小括号内联复合表达式: ({...})
类似@[] == [nsarray arraywith….]这种,你可以看成编译器帮你简化方便写代码的一种方式。
A compound statement enclosed in parentheses
来自《gcc官方对此的说明》,源自gcc对c的扩展,如今被clang继承。
源代码定义:
RETURN_VALUE_RECEIVER = {(
// Do whatever you want
RETURN_VALUE; // 返回值
)};
有点像block和内联函数的结合体,它最大的意义在于将代码整理分块,将同一个逻辑层级的代码包在一起;同时对于一个无需复用小段逻辑,也免去了重量级的调用函数,如:
self.result = ({
double result = 0;
for (int i = 0; i <= M_2_PI; i+= M_PI_4) {
result += sin(i);
}
result;
});
这样使得代码量增大时层次仍然能比较明确。
PS: 返回值和代码块结束点必须在结尾
使用例子
例子1:
self.testBtn = ({
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(100, 10, 100, 44);
[button setTitle:@"测试" forState:UIControlStateNormal];
button;
});
例子2:
// 添加myTableView
_myTableView = ({
UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
tableView.backgroundColor = [UIColor clearColor];
tableView.dataSource = self;
tableView.delegate = self;
tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
[tableView registerClass:[TweetCell class] forCellReuseIdentifier:kCellIdentifier_Tweet];
[self.view addSubview:tableView];
[tableView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.view);
}];
{
__weak typeof(self) weakSelf = self;
[tableView addInfiniteScrollingWithActionHandler:^{
[weakSelf refreshMore];
}];
}
{
UIEdgeInsets insets = UIEdgeInsetsMake(0, 0, CGRectGetHeight(self.rdv_tabBarController.tabBar.frame), 0);
tableView.contentInset = insets;
}
tableView;
});