在 OC 中语法糖应用形式一般如下:
self.bgView = ({
UIView *view = [[UIView alloc] init];
view.layer.cornerRadius = 5;
view.layer.masksToBounds = YES;
view.backgroundColor = self.layout.searchBGColor;
[self addSubview:view];
view;
});
这里语法糖的使用有利于把代码集中便于阅读;
通过对上面语法糖的观察我们可以得出在 ({}) 中,只需要在 {} 的最后一行返回一个 value 即可(我们是不是应该认为 ({}) 的本质是一个 表达式 ),那么我们就可以做一些有意思的事情了:
-
基本数据类型中使用
({}),如下module.totalHeight = ({ 128.0; }); -
三目运算符中
例如在
-tableView:heightForRowAtIndexPath:中我们使用model进行缓存cell高度时一般情况代码会这样:- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { APNTaskListModel *module = _data[indexPath.row]; if (module.totalHeight < 1.0) { module.totalHeight = [APNTaskListCell defaultHeight] + [APNTaskListCell increasedHeightWithName:module.apnTaskName]; } return module.totalHeight; }有了
({})后你可以使用三目运算符来省略if判断,如下- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { APNTaskListModel *module = _data[indexPath.row]; return module.totalHeight > 1.0 ? module.totalHeight : ({ module.totalHeight = [APNTaskListCell defaultHeight] + [APNTaskListCell increasedHeightWithName:module.apnTaskName]; module.totalHeight; }); }再来一个?
model.showRightArrow ? ({ // 这里也可以封装为函数 self.rightArrowImgView.hidden = NO; self.rightArrowImgView.image = model.rightArrowIcon; self.spaceForDetail.constant = 33; }) : ({ self.rightArrowImgView.hidden = YES; self.spaceForDetail.constant = 15; });emmm... 下一个.
-
在自定义宏函数中的使用:
一般我们会在项目中自定义一些宏,在区分
debug模式和release模式,如下一个简单的例子:#ifdef DEBUG #define DR_SimpleLog(...) NSLog(__VA_ARGS__) #else #define DR_SimpleLog(...) #endif当我们在使用时可能会碰到一种情况,我想要在
debug模式下看到某个计算方法被调用的次数时,可能会出现如下代码:static NSInteger i = 0; DR_SimpleLog(@"计算了:%@次",@(++i));但是这个
static变量i,我们不想让它在release模式下存在,so:DR_SimpleLog(@"计算了:%@次",({ static NSInteger i = 0; @(++i); }));