views:

240

answers:

4

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;
}
+3  A: 

A bit dummy example:

- (NSArray*) test{
  return [NSArray arrayWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:2], nil];
}

Some notes:

  • NSArray is a immutable type - so if you want to add/remove values you should use NSMutableArray instead
  • You can store only objects in NSArray so you need to wrap them into NSNumber (or another obj-c type)
  • Obj-c is a superset of C so you can freely use c-arrays in you obj-c code if you want
Vladimir
+2  A: 

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 autoreleased 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];
}
Steve Harrison
Thank you very much.
aon
+1  A: 

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];
Chuck
+2  A: 

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;
}
Vincent Osinga