Objective C: NSRange or similar with float?

2020-03-24 06:15发布

For some methods I want them to return a range of values (from: 235, to: 245). I did this using NSRange as a return value

- (NSRange)giveMeARangeForMyParameter:(NSString *)myParameter;

This works fine as long as the return value is an integer range (e.g. location: 235, length: 10).

But now I have the problem that I need to return a float range (e.g. location: 500.5, length: 0.4). I read in the doc that NSRange is a typedefed struct with NSUIntegers. Is it possible to typedef another struct for float ranges? And if so, can there be a similar method to NSMakeRange(NSUInteger loc, NSUInteger len) to create those float ranges?

4条回答
Anthone
2楼-- · 2020-03-24 06:45

Although you could reuse one of several "pair objects" from the graphics library (you can pick from a CGPoint or CGSize, or their NS... equivalents) the structs behind these objects are so simple that it would be better to create your own:

typedef struct FPRange {
    float location;
    float length;
} FPRange;

FPRange FPRangeMake(float _location, float _length) {
    FPRange res;
    res.location = _location;
    res.length = _length;
    return res;
}
查看更多
▲ chillily
3楼-- · 2020-03-24 06:50

With the introduction of the IOS 9 SDK, a new structure has been added by Apple which best match the OP subject:

UIFloatRange UIFloatRangeMake(CGFloat minimum, CGFloat maximum); // The range of motion for attached objects.

There are couple of useful helper functions to compare ranges too:

BOOL UIFloatRangeIsInfinite(UIFloatRange range);
BOOL UIFloatRangeIsEqualToRange(UIFloatRange range, UIFloatRange otherRange);
查看更多
等我变得足够好
4楼-- · 2020-03-24 06:59

Yes, you can even go and look at the definitions of NSRange and NSMakeRange (in NSRange.h, easiest way to get there is to 'command click' on NSRange name in Xcode) to see how to do it:

typedef struct _NSRange {
    NSUInteger location;
    NSUInteger length;
} NSRange;

NS_INLINE NSRange NSMakeRange(NSUInteger loc, NSUInteger len) {
    NSRange r;
    r.location = loc;
    r.length = len;
    return r;
}
查看更多
走好不送
5楼-- · 2020-03-24 06:59

If you just want an existing struct with 2 floats and you don't mind including GLKit, you could use GLKVector2. It also has a Make function.

查看更多
登录 后发表回答