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. chlebsonification reblogged this from alldonegoodbye
  2. alldonegoodbye reblogged this from cocoa-dom
  3. blistering-pree 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.
  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-blog-blog 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. whatcode reblogged this from cocoa-dom and added:
    Interesting :)
  12. sgamel reblogged this from cocoa-dom
  13. frijole reblogged this from cocoa-dom and added:
    Fascinating.
  14. cocoa-dom posted this