1

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

4 Answers 4

5

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];
}
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

2

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

Comments

1

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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.