Code below is a simple c# function return an int array. I would like to know how to convert it to Objective-C
private int[] test()
{
int[] a = new int[2];
a[0] = 1;
a[1] = 2;
return a;
}
Code below is a simple c# function return an int array. I would like to know how to convert it to Objective-C
private int[] test()
{
int[] a = new int[2];
a[0] = 1;
a[1] = 2;
return a;
}
A bit dummy example:
- (NSArray*) test{
return [NSArray arrayWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:2], nil];
}
Some notes:
The following code should work:
- (NSArray *)test {
NSArray *a = [NSArray arrayWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:2], nil];
return a;
}
Note that if we created the NSArray
using [[NSArray alloc] initWithObjects:blah, blah, nil];
, we'd have to explicitly autorelease
the array before returning it in order to avoid a memory leak. In this case, however, the NSArray
is created using a convenience constructor, so the array is already autorelease
d for us.
Second Question:
Try this:
- (NSMutableArray *)test:(int)count {
NSMutableArray *a = [[NSMutableArray alloc] init];
for (int i = 0; i < count; i++) {
[a insertObject:[NSNumber numberWithInt:0] atIndex:i];
}
return [a autorelease];
}
There are two kinds of array in Objective-C: standard C arrays and Cocoa NSArrays. C arrays hold primitive ints but are quite troublesome due to the limitations of C. NSArrays have to hold objects, but you can just wrap ints in NSNumbers and get the int value back out when you need it.
NSArray *array = [NSArray arrayWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:500], [NSNumber numberWithInt:12000], nil];
Or an alternative path would be to use normal c code (is allowed in objective c):
int a[2]={1, 2};
Or in a function:
int *somefunc(void){
static int a[2]={1, 2};
return b;
}