从NSNumber获取CGFloat最常见和最正确的做法是什么? [英] What is most common and correct practice to get a CGFloat from an NSNumber?

查看:765
本文介绍了从NSNumber获取CGFloat最常见和最正确的做法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作代码是:

NSNumber *n = @42.42;
CGFloat cgf = 0; 
CFNumberRef cfn = CFBridgingRetain(n);
CFNumberGetValue(cfn, kCFNumberCGFloatType, &cgf);
CFRelease(cfn);

也可以

CGFloat cgf = (CGFLOAT_IS_DOUBLE) ? [n doubleValue] : [n floatValue];

但这对我来说更难闻。

在我看来,应该有更好的API做这样一个普通的事情。有什么吗?

It seems to me there should be better API for doing such a common thing. Are there any?

推荐答案

在任何情况下都会得到正确的结果:

This will get the correct result in any case:

 NSNumber *n = @42.42;
 CGFloat cgf = [n doubleValue];

因为 CGFloat c> float 或 double

because CGFloat is either float or double.

NSNumber 没有 CGFloatValue 方法。您可以使用 CFNumberRef 的免费桥梁定义一个

NSNumber does not have a CGFloatValue method. You could define one using the toll-free bridge to CFNumberRef:

@interface NSNumber (MyCGFloatValue)
-(CGFloat)myCGFloatValue;
@end

@implementation NSNumber (MyCGFloatValue)
-(CGFloat)myCGFloatValue{
    CGFloat result;
    CFNumberGetValue((__bridge CFNumberRef)(self), kCFNumberCGFloatType, &result);
    return result;
}
@end

或使用C11功能通用选择其中编译器根据 CGFloat 的类型选择适当的
代码:

or using the C11 feature "Generic selection", where the compiler chooses the appropriate code depending on the type of CGFloat:

@implementation NSNumber (MyCGFloatValue)
-(CGFloat)myCGFloatValue{
    CGFloat result;
    result = _Generic(result,
            double: [self doubleValue],
            float: [self floatValue]);
    return result;
}
@end

然后

NSNumber *n = @42.24;
CGFloat f = [n myCGFloatValue];

但我怀疑这是值得的麻烦。

but I doubt that it is worth the hassle.

这篇关于从NSNumber获取CGFloat最常见和最正确的做法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆