Is C99 designated initializers or the various CGSizeMake, CZRectMake, etc macros more preferable as convention in modern Objective-C?
Neither style is objectively preferable in general. The formats of the CGRect
, CGPoint
, and CGSize
structures are part of the public documentation, and thus effectively as unchangeable as the order of arguments to CGRectMake
, so using a literal is fine. Whether to use literals or the Make
functions is a matter of personal taste.
I tend to use CGRectMake
instead of a literal when I have all the coordinates easily accessible. I prefer a literal when I'd otherwise have to either use an extra statement or send a message twice. For example, suppose I want to make a rectangle whose origin is (0,0) and whose size is the size of view
. I could do that with CGRectMake
like this:
CGRect rect = CGRectMake(0, 0, view.bounds.size.width, view.bounds.size.height);
But then I'm sending the bounds
message twice. I could send it just once like this:
CGRect rect = view.bounds;
rect.origin = CGPointZero;
Or like this:
CGRect size = view.bounds.size;
CGRect rect = CGRectMake(0, 0, size.width, size.height);
But I prefer to use a literal like this:
CGRect rect = (CGRect){ .origin = CGPointZero, .size = view.bounds.size };
What's the reason people would continue using the existing macros?
Familiarity. Many people aren't familiar with the literal syntax, and they won't learn it by reading Apple's documentation.
A form of safety. If you use the macro, you're forced to provide all of the structure elements. You can't accidentally omit one.
On the other hand, you must put the elements in the correct order. So it's not strictly safer than a literal.