Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
543 views
in Technique[技术] by (71.8m points)

ios - What is most common and correct practice to get a CGFloat from an NSNumber?

The working code for me is something like:

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

There could be also

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

But this smells even uglier for me.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This will get the correct result in any case:

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

because CGFloat is either float or double.


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

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

And then

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

but I doubt that it is worth the hassle.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...