how to convert a range to NSArray in Objective-C

后端 未结 4 967
囚心锁ツ
囚心锁ツ 2020-12-19 15:42

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

相关标签:
4条回答
  • 2020-12-19 15:56

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

    0 讨论(0)
  • 2020-12-19 15:58

    You might want to try NSIndexSet instead.

    NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(1, 100)];
    
    0 讨论(0)
  • 2020-12-19 16:11

    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]];
    }
    
    0 讨论(0)
  • 2020-12-19 16:18

    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.

    0 讨论(0)
提交回复
热议问题