将nil发送到CGPoint类型参数

时间:2012-08-16 12:29:12

标签: objective-c

假设我有这个方法:

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

所以我将视图和一个点传递给视图的中心。

但碰巧我不需要指定中心,只需要指定视图。

传递“nil”会导致错误。

请建议如何跳过中心点。

请记住,我需要使用这样的方法:

- (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
    }
}

提前致谢

2 个答案:

答案 0 :(得分:12)

您不能将nil用作“无点”指示符,因为它仅适用于对象,CGPointstruct。 (正如dasblinkenlight已经说过的那样。)

在我的几何库中,我定义了一个“null”CGPoint用作“无点”占位符,以及一个测试它的函数。由于CGPoint的组件为CGFloat s,而float s已经具有“无效值”表示 - NAN,在math.h中定义 - 我认为这是最好用的:

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

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

BOOL WSSCGPointIsNull( CGPoint point ){
    return isnan(point.x) && isnan(point.y);
}

答案 1 :(得分:5)

CGPoint是C struct,您无法通过nil。您可以创建一个单独的方法,不会使用不必要的CGPoint,并删除您的if语句,如下所示:

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

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

如果您坚持保留一种方法,则可以将一个点指定为“特殊”(例如CGMakePoint(CGFLOAT_MAX, CGFLOAT_MAX)),将其包装在#define中,然后使用而不是nil

另一种解决方案是将CGPoint包裹在NSValue

NSValue *v = [NSValue withPoint:CGMakePoint(12, 34)];
CGPoint p = [v pointValue];