开发者

Is it wrong to use functions like CGRectMake in a method rather than creating a variable first?

for example:

someView = [[UIView alloc] initWithFra开发者_JAVA技巧me:CGRectMake(120, 205, 200, 200)];

rather than:

CGRect frame = CGRectMake(120, 205, 200, 200);
someView = [[UIView alloc] initWithFrame:frame];

I seems like I only see the second example. Is it just for readability? Or is there a good reason for this?


It's just a matter of style. The two are equivalent and will probably compile to the same thing.


Only difference is as you already pointed out, readability. It also makes the CGRect structure reusable other places in your code if you need the same dimensions.


Both pieces of code have identical effect. There could be a couple of reasons for using the second pattern:

  • The code can be easier to read. You can name the variable to be more descriptive.

  • If you're reusing the same rect many times, it might make sense to declare it once and reuse it. While CGRectMake is an inexpensive operation, it could still be a good practice, especially if you're running this code many times in a loop.


The problem with the second option, is if you make a lot of CGRects in the same scope, you'll need to either prevent your code from redefining frame, overwrite the variable, or come up with different names for different frames.

To make your code more portable, I would go with the first option every time. But if it got a little too complex, then I'd split it out for readability's sake.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜