Cocoa and iOS Development

Archive for the ‘inline functions’ tag


leave a comment

Earlier this week I noticed that the CGGeometry class does not contain any convenience methods (besides CGSizeEqualToSize) for comparing one CGSize to another.  What I was looking for was a method to tell me if one size was greater than another. Joe brought up an interesting point- what exactly does it mean for one size to be greater than another? Having a larger width? Larger height? Both larger height and width? In my use case, a size should be considered greater than another size if either its width or height are larger, however I understand how this might differ in other applications (in fact, I vacillated between requiring both width and height to be larger). My solution was to create a category for CGGeometry and define an inline function:

__CGSizeGreaterThanSize(CGSize size1, CGSize size2) {
return size1.width > size2.width || size1.height > size2.height;
#define CGSizeGreaterThanSize __CGSizeGreaterThanSize

A lot of neat things are happening here so lets take a closer look. CG_INLINE is actually a macro that is telling the compiler that what follows should  be marked as an inline function. This saves us from having to write a few extra lines of code to determine the correct syntax for our compiler. Take a look at the Adam Wright’s response to this StackOverflow post for different inline function syntax examples.

What follows after CG_INLINE is the function return type (bool) and then the function definition. Our function name (__CGSizeGreaterThanSize) takes two parameters, size1 and size2 and returns YES if either size1′s width or height is greater than size2′s and NO if not.

#define is a very common preprocessor directive that allows you to define constants, macros, and in our case, inline functions. What we are doing here is saying future calls to CGSizeGreaterThanSize should invoke the function __CGSizeGreaterThanSize. Note that __CGSizeGreaterThanSize isn’t significant, just intuitive. We could have used any other name in its place.

This simple method helps us maintain clarity within our code. When CGSizeGreaterThanSize(aSize, anotherSize) is called, the code in our function body replaces the call to the function. This is significant because it means that we don’t transfer the control from the program to the function. Instead, we maintain within the program and CGSizeGreaterThanSize is not placed on our stack. Cool!

Written by Sarah

February 11th, 2012 at 6:38 pm