This is from a category that I’m using to modify UIView. The code works, but in the first method (setFrameHeight) I’m using a block and in the second method (setFrameWidth) I’m not. Is there any way to use blocks more efficiently in this example?
typedef CGRect (^modifyFrameBlock)(CGRect);
- (void) modifyFrame:(modifyFrameBlock) block {
self.frame = block(self.frame);
}
- (void) setFrameWidth:(CGFloat)newWidth {
modifyFrameBlock b = ^CGRect (CGRect frame) {
frame.size.width = newWidth;
return frame;
};
[self modifyFrame:b];
}
- (void) setFrameHeight:(CGFloat)newHeight {
CGRect f = self.frame;
f.size.height = newHeight;
self.frame = f;
}
The answer may be that blocks are not appropriate for such short methods, or something. The syntax sure seems funky.
The only thing you gain is not declaring the local variable for the new rect, in exchange you need to define a block. That is not a good deal, especially as it distracts from what you are doing.
Note that your block-usage could be shortened a bit:
Or even:
With
modifyFrame:being:But i’d still limit such approaches to more complex methods that only require minor parts of the code to be different.