美文网首页
OC的小括号内联复合表达式,(厉害啊: UIView)

OC的小括号内联复合表达式,(厉害啊: UIView)

作者: FlyTheKite | 来源:发表于2016-10-24 16:26 被阅读68次

OC的小括号内联复合表达式
A compound statement enclosed in parentheses

RETURN_VALUE_RECEIVER = {(
    // Do whatever you want
    RETURN_VALUE; // 返回值
)};

这样写比较少见,

 例子1

[self.view addSubview:({
        _addPhotoButton = [UIButton buttonWithType:UIButtonTypeContactAdd];
        _addPhotoButton.frame = CGRectMake(0, 25, 44, 44);
        [_addPhotoButton addTarget:self action:@selector(addPhotoButtonClick) forControlEvents:UIControlEventTouchUpInside];
        _addPhotoButton;
    })];
    ```


 例子2


[self.view addSubview:({

    [[UIView alloc ] init ];
}) ];

#优点:
 有点像block和内联函数的结合体,它最大的意义在于将代码整理分块,将同一个逻辑层级的代码包在一起;
同时对于一个无需复用小段逻辑,也免去了重量级的调用函数。这样使得代码量增大时层次仍然能比较明确。
此外,返回值和代码块结束点必须在结尾。


## 引用文档:
[objc非主流代码技巧](http://blog.sunnyxx.com/2014/08/02/objc-weird-code/)

相关文章

网友评论

      本文标题:OC的小括号内联复合表达式,(厉害啊: UIView)

      本文链接:https://www.haomeiwen.com/subject/mquluttx.html