将nil发送到CGPoint类型参数

Joh*_*ith 5 objective-c

假设我有这个方法:

- (void)placeView:(UIView*)theView withCenterIn:(CGPoint)centerPoint;
Run Code Online (Sandbox Code Playgroud)

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

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

传递"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
    }
}
Run Code Online (Sandbox Code Playgroud)

提前致谢

Jos*_*ell 12

你不能nil用作"无点"指标,因为它只适用于对象,而且CGPoint是一个struct.(正如dasblinkenlight已经说过的那样.)

在我的几何库中,我定义了一个"null" CGPoint用作"无点"占位符,以及一个测试它的函数.由于a的组件CGPointCGFloats,并且floats已经具有"无效值"表示 - 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);
}
Run Code Online (Sandbox Code Playgroud)


das*_*ght 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
}
Run Code Online (Sandbox Code Playgroud)

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

另一个解决方案是包装你CGPointNSValue:

NSValue *v = [NSValue withPoint:CGMakePoint(12, 34)];
CGPoint p = [v pointValue];
Run Code Online (Sandbox Code Playgroud)