4

I know how to do it in Ruby, converting a range of numbers to an array. But how is it possible in Objective-C?

Ruby: (1..100).to_a

Monolo
  • 18,205
  • 17
  • 69
  • 103
joostevilghost
  • 149
  • 3
  • 7
  • possible duplicate of [looping using NSRange](http://stackoverflow.com/questions/8320987/looping-using-nsrange) – jscs Feb 25 '12 at 19:15
  • Restumbled upon this question. At the risk of promoting my own answer... I would like to point out that it actually IS POSSIBLE, just not with NSArray. You can do this with NSIndexSet, which is fine because in a range all the values are unique anyway—you don't need NSArray. You can probably do everything you want to do with NSIndexSet in this case. (see my answer below). – Jarsen Dec 06 '13 at 16:00

4 Answers4

8

You've got to do it manually:

// Assuming you've got a "NSRange range;"
NSMutableArray *array = [NSMutableArray array];
for (NSUInteger i = range.location; i < range.location + range.length; i++) {
    [array addObject:[NSNumber numberWithUnsignedInteger:i]];
}
DarkDust
  • 90,870
  • 19
  • 190
  • 224
4

You might want to try NSIndexSet instead.

NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(1, 100)];
Jarsen
  • 7,432
  • 6
  • 27
  • 26
4

Just to throw a whacky solution in from the left:

The idea is to have the Key-Value Coding machinery create the array for you, through indexed properties.

Interface:

@interface RangeArrayFactory : NSObject {
    NSRange range;
}
@end

Implementation:

- (id)initWithRange: (NSRange)aRange
{
    self = [super init];
    if (self) {
        range = aRange;
    }
    return self;
}

// KVC for a synthetic array

- (NSUInteger) countOfArray
{
    return range.length;
}


- (id) objectInArrayAtIndex: (NSUInteger) index
{    
    return [NSNumber numberWithInteger:range.location + index];
}

Use:

NSRange range = NSMakeRange(5, 10);

NSArray *syntheticArray = [[[RangeArrayFactory alloc] initWithRange: range] valueForKey: @"array"];

This solution is mostly for fun, but it might make sense for large ranges, where a real array filled with consecutive numbers will take up more memory than is actually needed.

As noted by Rob Napier in the comments, you could also subclass NSArray, which just requires you to implement count and objectForIndex:, using the same code as countOfArray and objectInArrayAtIndex above.

Monolo
  • 18,205
  • 17
  • 69
  • 103
  • Excellent example of KVC collection methods. Note that you could just as easily subclass `NSArray` in the same way (overriding `count` and `objectAtIndex:`). On a related note, though it's not promised by the API, the integer `NSNumber` objects from -1 to 12 happen to be singletons. That fact is sometimes useful when you're concerned about creating small numbers over and over again. – Rob Napier Jun 28 '12 at 05:51
1

You'll need to write a simple loop. There isn't any "range of numbers" operator in Objective-C.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610