Search code examples
iosobjective-cnsarray

iOS - Initializing an NSArray with a sequence of numbers


I'm looking to do something in Objective C equivalent to the following MATLAB command:

A=4:7; 

In this case, the variable A then becomes an array with elements [4 5 6 7].

Is there any shorthand way to set an NSArray with a sequence of numbers like this in Objective C? Thanks for reading!


Solution

  • Thanks for the replies everyone. So far, I'm just using a loop:

    NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:4];
    for (int i=0; i<4; i++) {
        int value=i+4;
        [mutableArray addObject:[NSNumber numberWithInt:value]];
    }
    NSArray *finalArray=[NSArray arrayWithArray:mutableArray];
    

    It doesn't appear that using NSIndexSet does the same thing (Thanks, Martin R and BergQuester), but if anyone has a more efficient way to do this, I'd definitely be interested.