赋值的另一种写法

Ever since I found out that a GCC C extension causes a code block to return a value if you enclose it in round brackets, I’ve been using it in my code. What do you think?

self.bounds = ({
	CGRect bounds = self.bounds;
	bounds.size.height = self.currentYPosition + SHEETINSETY;
	bounds;
});

I’m also using this for frame. The advantage is that with this construct I never forget to set the frame after altering it, which I did far too often otherwise.

self.helpButton = ({	// helpbutton
  UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
  [button setImage:[UIImage imageNamed:@"ParentalControlQuestionMarkButton"] forState:UIControlStateNormal];
  CGRect buttonRect = innerBounds;
  buttonRect.size = [button sizeThatFits:CGSizeMake(400, 400)];
  buttonRect.origin.x = CGRectGetMaxX(innerBounds)-CGRectGetWidth(buttonRect);
  button.frame = UIEdgeInsetsInsetRect(buttonRect, UIEdgeInsetsMake(0, -10, -20, -10));
  [button addTarget:self action:@selector(helpAction:) forControlEvents:UIControlEventTouchUpInside];
  [self addSubview:button];
  button;
});

The major benefits of this one are:

  • the instance variable in which I will store the generated object is in the first line, clearly showing what the next part of the code does. Prior to this, the assignment happend at the end.
  • the stack variables declared and used don’t pollute other code in the same function/method. I can feel free to use very generic names (view,frame,rect,button) and not get into conflict with other parts.

Update: And it all works with CLANG due to the great design policy of CLANG to support most of the GCC extensions to maximise compatibility. 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值