NSNumber from CGFloat

2020-07-05 20:06发布

Is there a safe way to "convert" a CGFloat to a NSNumber ?

NSNumber has the numberWithFloat: and numberWithDouble: methods but CGFloat being defined as float or double depending on the platform, it seems risky to use either one of them.

Or is numberWithDouble: safe to use with a CGFloat, as it is the one with the more precision ?

2条回答
我欲成王,谁敢阻挡
2楼-- · 2020-07-05 20:33

I believe @ NSNumber literal is good enough

@(myCGFloat)

Read more here: http://clang.llvm.org/docs/ObjectiveCLiterals.html

查看更多
做自己的国王
3楼-- · 2020-07-05 20:46

This is how I handled it:

@interface NSNumber (CGFloatAdditions)

+ (NSNumber*)numberWithCGFloat: (CGFloat)value;
- (CGFloat)CGFloatValue;

@end

@implementation NSNumber (CGFloatAdditions)

+ (NSNumber*)numberWithCGFloat: (CGFloat)value
{
#if CGFLOAT_IS_DOUBLE
    return [NSNumber numberWithDouble: (double)value];
#else
    return [NSNumber numberWithFloat: value];
#endif
}

- (CGFloat)CGFloatValue
{
#if CGFLOAT_IS_DOUBLE
    return [self doubleValue];
#else
    return [self floatValue];
#endif
}


@end

CGFLOAT_IS_DOUBLE is defined in CGBase.h conditionally by platform.

查看更多
登录 后发表回答