Rogare
Rogare

Reputation: 3274

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!

Upvotes: 3

Views: 1082

Answers (4)

David Hoerl
David Hoerl

Reputation: 41642

Use a NSIndexSet as the object in the array - you can then use:

[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(4, 4)];

Upvotes: 4

Rogare
Rogare

Reputation: 3274

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.

Upvotes: 0

user1411443
user1411443

Reputation:

use NSIndexSet object:

NSArray *seqArray = [NSArray arrayWithObjects:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(4, 3)], nil];

ADDED: or in newer xcodes:

NSArray *seqArray = @[[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(4, 3)]];

Upvotes: 1

Ponting
Ponting

Reputation: 2246

i think simplest way to use for loop in your case.

Upvotes: 1

Related Questions