Tutorial :Writing a Macro for this: (Objective-C)



Question:

I have a method like this:

- (CGPoint) _convertCGPointCT2UIKit:(CGPoint)ctPoint{   CGPoint uikitPoint = CGPointMake(ctPoint.x + INITIAL_HORIZ_OFFSET,             self.bounds.size.height - ctPoint.y - INITIAL_VERT_OFFSET);   return uikitPoint;  }  

Is there any way I can make this a macro? I tried this but I get errors like "; expected before )" and so on.

#define CGPointUIKit2CT(p) CGPointMake(p.x - INITIAL_HORIZ_OFFSET, self.bounds.size.height - p.y - INITIAL_VERT_OFFSET);  

thanks in advance.

Ignacio


Solution:1

A couple of rules of thumb to guide you:

  • Wrap everything in parentheses
  • Don't end a macro with a semicolon, that's probably what's generating your errors. Instead put the semicolon in your code when you use it.

Here's my answer:

 #define CGPointUIKit2CT(p) CGPointMake(((p).x) - INITIAL_HORIZ_OFFSET, self.bounds.size.height - ((p).y) - INITIAL_VERT_OFFSET)  


Solution:2

While there may be reasons to avoid method dispatch for something like this, there is no reason to do it as a macro instead of a static inline function:

static inline  CGPoint CGPointUIKit2CT(UIView *self, CGPoint  ctPoint) {    CGPoint uikitPoint = CGPointMake(ctPoint.x + INITIAL_HORIZ_OFFSET,        self.bounds.size.height - ctPoint.y - INITIAL_VERT_OFFSET);'      return uikitPoint;  }  

That will compile out to the same thing as a macro, but will provide better debugging and profiling information.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »