If you are doing this for an app written in Objective-C, I would suggest using NSArray
. NSArray
is an Objective-C class for immutable arrays, and doesn't require that you manually allocate memory. The only turnoff is that you have to encapsulate your integers in NSNumber
objects. An example would be:
NSArray * getNums (int num) {
NSArray * result = [NSArray arrayWithObjects:[NSNumber numberWithInt:num-1], [NSNumber numberWithInt:num], [NSNumber numberWithInt:num+1], nil];
return result;
}
...
NSArray * myList = getNums(10);
NSLog(@"First: %d", [[myList objectAtIndex:0] intValue]);
NSLog(@"Second: %d", [[myList objectAtIndex:1] intValue]);
NSLog(@"Third: %d", [[myList objectAtIndex:2] intValue]);
You can alternatively do this:
NSArray * getNums (int num) {
NSMutableArray * array = [NSMutableArray array];
[array addObject:[NSNumber numberWithInt:num-1]];
[array addObject:[NSNumber numberWithInt:num]];
[array addObject:[NSNumber numberWithInt:num+1]];
return array;
}
...
NSArray * myList = getNums(10);
for (int i = 0; i < [myList count]; i++) {
NSLog(@"myList[%d] = %d", i, [myList objectAtIndex:i]);
}
The only difference is that NSMutableArray allows you to add/remove elements after the fact.