Reputation: 3274
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
Reputation: 41642
Use a NSIndexSet as the object in the array - you can then use:
[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(4, 4)];
Upvotes: 4
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
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