Monday August 05, 2013

Why Use CGRectMake and Friends?

Update: Apparently CGRectMake does not standardize coordinates like the other CGGeometry functions. Now I’m even more confused.

While browsing the freshly released Objective-C style guide from Matt Bischoff of the New York Times, I did a double take when I reached the part about the CGRect. Matt’s citation of Apple’s documentation on the CGGeometry functions surprised me:

The height and width stored in a CGRect data structure can be negative. For example, a rectangle with an origin of [0.0, 0.0] and a size of [10.0,10.0] is exactly equivalent to a rectangle with an origin of [10.0, 10.0] and a size of [-10.0,-10.0]. Your application can standardize a rectangle—that is, ensure that the height and width are stored as positive values—by calling the CGRectStandardize function. All functions described in this reference that take CGRect data structures as inputs implicitly standardize those rectangles before calculating their results. For this reason, your applications should avoid directly reading and writing the data stored in the CGRect data structure. Instead, use the functions described here to manipulate rectangles and to retrieve their characteristics.

In summary, Apple recommends using the CGGeometry functions because they want to ensure all rectangles are “standardized” with the dimensions always expressed in positive values. It makes me wonder if there aren’t some special optimizations that happen under the hood if CGRects are guaranteed to be standard in this way1.

  1. For contrast, Github’s style guide intrigues me because they chose to prefer C99 struct initializer syntax, which obviously does not guarantee “standardized” CGRects.