cocoa-dom

cocoa bits I use, come across, like, hate, the whole shebang.

twitter | adn         rant-dom | TCM        github         rss | archive
July 26, 2013 at 10:19am
Home

New thing I do in code

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. 

Notes

  1. nicedexter reblogged this from cocoa-dom
  2. paulrehkugler reblogged this from cocoa-dom and added:
    This is one of those really smart things I haven’t seen in Apple’s sample code yet.
  3. brainmess reblogged this from cocoa-dom
  4. ura-urashima reblogged this from cocoa-dom and added:
    便利そう!
  5. wataruhash reblogged this from cocoa-dom
  6. dsavindev reblogged this from cocoa-dom
  7. zhocker reblogged this from clonez
  8. clonez reblogged this from cocoa-dom and added:
    เห้ยย ทำอย่างงี้ได้ด้วย >
  9. niueeee reblogged this from cocoa-dom
  10. ilwoody reblogged this from cocoa-dom and added:
    I’m not sure I like this yet but it may become handy to cleanup some code of mine
  11. slowfocus reblogged this from cocoa-dom
  12. imtimuy reblogged this from cocoa-dom
  13. whatcode reblogged this from cocoa-dom and added:
    Interesting :)
  14. sgamel reblogged this from cocoa-dom and added:
    Nice Obj-C trick. Might be useful.
  15. frijole reblogged this from cocoa-dom and added:
    Fascinating.