0

I have a general question. is there a way to have a range of double object in Objective-C? I am trying to create a dictionary with different double ranges as values.

I have the following as keys:

 NSArray *keys = @[@"Severe Thinness",@"Moderate Thinness",@"Mild Thinness",
                   @"Normal Range",@"Overweight",@"Obese Class I (Moderate)",
                   @"Obese Class II (Severe)",@"Obese Class III (Very Severe)"];

in order to create the range objects, I was trying to create such array:

NSArray *values = @[NSMakeRange(1,3),
                       NSMakeRange(16, 16.99),
                       NSMakeRange(17, 18.49),
                       NSMakeRange(18.50, 24.99),
                       NSMakeRange(25, 29.99),
                       NSMakeRange(30, 34.99),
                       NSMakeRange(35, 39.99),
                       NSMakeRange(40, 100)];

but this approach causes an error because NSMakeRange does not create objects.

Master Stroke
  • 5,108
  • 2
  • 26
  • 57
RazorHead
  • 1,460
  • 3
  • 14
  • 20

3 Answers3

2

NSRange is defined using NSUIntegers. If you want something similar, you can define your own struct using the same pattern:

typedef struct _MYDoubleRange {
      double location;
      double length;
} MYDoubleRange;

But location and length may not make sense as doubles and you won't be able to store the MYDoubleRange in an NSArray directly. I would define an object:

@interface MYDoubleRange : NSObject
@property(nonatomic,assign) double start;
@property(nonatomic,assign) double end;
@end

And then you can add whatever methods you need to compare, etc.

i_am_jorf
  • 53,608
  • 15
  • 131
  • 222
1

You have two problems. One, you want a range that handles floats, and second you want to put that into an NSArray.

Touching on the second problem, NSArray won't accept primitives. I've never tested if there's a way around the problem, but in general you only put NSObject and NSObject subclasses into NSArrays. (Fun fact: almost all objects in cocoa and cocoa touch are, in fact, NSObject subclasses! It's the root of... well, everything!)

What you probably need to do is roll your own custom NSObject subclass that encapsulates the logic you need, and then use that.

RonLugge
  • 5,086
  • 5
  • 33
  • 61
0

There is nothing in the standard library to allow you to create a range(NSRange) with doubles. But of course you can create your own range object. If you are a little more descriptive of what you need the range for (i.e what it is to represent ... etc) I am happy to try and help.

Jesse Nelson
  • 776
  • 8
  • 21