使用块缩短我的 Objective-C 代码
这是我用来修改 UIView 的类别。该代码有效,但在第一个方法(setFrameHeight)中我使用了一个块,而在第二个方法(setFrameWidth)中我没有使用。在这个例子中,有什么方法可以更有效地使用块吗?
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;
}
答案可能是块不适合这么短的方法,或者其他什么。语法确实看起来很时髦。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您获得的唯一好处是无需声明新矩形的局部变量,作为交换,您需要定义一个块。这并不是一件好事,尤其是因为它会分散你正在做的事情的注意力。
请注意,您的块使用可以稍微缩短:
或者甚至:
使用
modifyFrame:
是:但我仍然将这种方法限制为更复杂的方法,只需要代码的一小部分不同。
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.
这种特殊的模式在其他情况下很有用(通常在运行时需要可扩展性的情况下),并且在 C 中经常看到用函数指针代替块(例如
qsort()
和bsearch()< /code>。)但是,对于仅更新字段,通常的方法是从更简单的方法调用更复杂的方法:
This particular pattern is useful in other situations (generally where extensibility is needed at runtime) and is frequently seen in C with function pointers in place of blocks (e.g.
qsort()
andbsearch()
.) For just updating a field, however, the usual way is to just call from the simpler method to the more complex one: