15

我正在查看REMenu lib代码,并看到一个 vars 被声明为带有({ ... }); .. 看起来像是惰性评估代码的“关闭”.. 我不知道.. 有人可以解释一下吗?

self.menuWrapperView = ({
        UIView *view = [[UIView alloc] init];
        view.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        if (!self.liveBlur || !REUIKitIsFlatMode()) {
            view.layer.shadowColor = self.shadowColor.CGColor;
            view.layer.shadowOffset = self.shadowOffset;
            view.layer.shadowOpacity = self.shadowOpacity;
            view.layer.shadowRadius = self.shadowRadius;
            view.layer.shouldRasterize = YES;
            view.layer.rasterizationScale = [UIScreen mainScreen].scale;
        }
        view;
    });

    self.toolbar = ({
        UIToolbar *toolbar = [[UIToolbar alloc] init];
        toolbar.barStyle = self.liveBlurBackgroundStyle;
        if ([toolbar respondsToSelector:@selector(setBarTintColor:)])
            [toolbar performSelector:@selector(setBarTintColor:) withObject:self.liveBlurTintColor];
        toolbar.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        toolbar;
    });
4

1 回答 1

22

这是一个 GNU(非标准)C 语言扩展,称为“<a href="http://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html#Statement-Exprs" rel="nofollow noreferrer" >语句表达式”。gcc、clang 和其他几个编译器都支持该语法。

基本上,它允许您将任意块​​视为单个表达式,其值是块中最后一条语句的值。

这个扩展最有用的是宏定义。在我看来,如果不使用语句表达式,您在问题中引用的代码(来自 中的showFromRect:inView:方法REMenu.m)会更好。相反,应该将这些语句表达式中的代码分解为单独的方法。例如:

    self.menuWrapperView = [self newMenuWrapperView];
    self.toolbar = [self newToolbar];

...

- (UIView *)newMenuWrapperView {
    UIView *view = [[UIView alloc] init];
    view.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    if (!self.liveBlur || !REUIKitIsFlatMode()) {
        view.layer.shadowColor = self.shadowColor.CGColor;
        view.layer.shadowOffset = self.shadowOffset;
        view.layer.shadowOpacity = self.shadowOpacity;
        view.layer.shadowRadius = self.shadowRadius;
        view.layer.shouldRasterize = YES;
        view.layer.rasterizationScale = [UIScreen mainScreen].scale;
    }
    return view;
}

- (UIToolbar *)newToolbar {
    UIToolbar *toolbar = [[UIToolbar alloc] init];
    toolbar.barStyle = self.liveBlurBackgroundStyle;
    if ([toolbar respondsToSelector:@selector(setBarTintColor:)])
        [toolbar performSelector:@selector(setBarTintColor:) withObject:self.liveBlurTintColor];
    toolbar.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    return toolbar;
}
于 2013-11-01T17:35:35.040 回答