NSNumber from CGFloat

旧街凉风 提交于 2019-12-05 17:49:48

问题


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 ?


回答1:


I believe @ NSNumber literal is good enough

@(myCGFloat)

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




回答2:


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.



来源:https://stackoverflow.com/questions/17067723/nsnumber-from-cgfloat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!