Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending nil to CGPoint type parameter

Tags:

objective-c

Suppose I have this method:

- (void)placeView:(UIView*)theView withCenterIn:(CGPoint)centerPoint;

So I pass the view and a point to te the view's center.

But it happens that I do not need to specify the center, just the view.

Passing "nil" leads to error.

Please, suggest how to skip passing the center point.

Keep in mind that I need to use that method like this:

- (void)placeView:(UIView*)theView withCenterIn:(CGPoint)centerPoint{
    if(centerPoint == nil){//and I understand that it's a wrong comparison, as I cannot pass "nil" to CGPoint
        //set a random center point
    }
    else{
        //set that view to the specified point
    }
}

Thanks in advance

like image 213
John Smith Avatar asked Aug 16 '12 12:08

John Smith


2 Answers

You can't use nil as a "no point" indicator, because it is only for objects, and CGPoint is a struct. (As dasblinkenlight has already said.)

In my geometry library, I've defined a "null" CGPoint to use as a "no point" placeholder, and a function to test for it. Since the components of a CGPoint are CGFloats, and floats have a "invalid value" representation already -- NAN, defined in math.h -- I think that's the best thing to use:

// Get NAN definition
#include <math.h>

const CGPoint WSSCGPointNull = {(CGFloat)NAN, (CGFloat)NAN};

BOOL WSSCGPointIsNull( CGPoint point ){
    return isnan(point.x) && isnan(point.y);
}
like image 61
jscs Avatar answered Oct 09 '22 09:10

jscs


CGPoint is a C struct, you cannot pass nil for it. You can create a separate method that does not take the unnecessary CGPoint, and get rid of your if statement, like this:

- (void)placeView:(UIView*)theView withCenterIn:(CGPoint)centerPoint{
    //set that view to the specified point
}

- (void)placeView:(UIView*)theView {
    //set a random center point
}

If you insist on keeping one method, you could designate one point as "special" (say, CGMakePoint(CGFLOAT_MAX, CGFLOAT_MAX)), wrap it in a #define, and use instead of nil.

Yet another solution would be to wrap your CGPoint in NSValue:

NSValue *v = [NSValue withPoint:CGMakePoint(12, 34)];
CGPoint p = [v pointValue];
like image 43
Sergey Kalinichenko Avatar answered Oct 09 '22 09:10

Sergey Kalinichenko