How to convert a range to NSArray in Objective-C

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

Ruby: (1..100).to_a

+4
source share
4 answers

You need 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]]; } 
+8
source

Just throw the punch to the left:

The idea is for the key-value encoding mechanism to create an array for you using 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]; } 

Using:

 NSRange range = NSMakeRange(5, 10); NSArray *syntheticArray = [[[RangeArrayFactory alloc] initWithRange: range] valueForKey: @"array"]; 

This solution is mainly for entertainment, but it may make sense for large ranges where a real array filled with sequential numbers will take up more memory than is really necessary.

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

+4
source

Instead, you can try NSIndexSet .

 NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(1, 100)]; 
+4
source

You need to write a simple loop. Objective-C does not have a "range of numbers" operator.

+1
source

Source: https://habr.com/ru/post/922026/


All Articles