Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass C array to a objective C method

I want to make an array of integers with as little code as possible and pass that array to an objective C method.

I tried the below. sequence starts out as an array and is passed to setLights: but when sequence is looked at in the method (via breakpoint) it is no longer an array.

*EDIT: I didnt want to use an NSArray because an NSArray of integers is so verbose:

Using NSArray:

NSArray *sequence = [[NSArray alloc] initWithObjects: [NSNumber numberWithInt:0], [NSNumber numberWithInt:1], [NSNumber numberWithInt:2], [NSNumber numberWithInt:3], [NSNumber numberWithInt:4],[NSNumber numberWithInt:5],nil];

Using C array:

int sequence[6] = {0,1,2,3,4,5};

What am I doing wrong?

- (IBAction)testLights:(id)sender {
    int sequence[6] = {0,1,2,3,4,5};
    //int *sequence[0][1][2][3][4][5]; //also tried this
    [self setLights:sequence];
}


- (void)setLights:(int *)sequence {

    UIImageView *light=[lgtArray objectAtIndex: sequence[0]];
    light.alpha = 0;
    [UIView animateWithDuration:0.3f
                     animations:^{
                         light.alpha = 1;
                     }completion:nil
     ];


}

enter image description here enter image description here

like image 343
Wesley Smith Avatar asked Apr 12 '26 02:04

Wesley Smith


2 Answers

Use this syntax to pass the array:

- (void)setLights:(int[] )sequence
like image 78
Enrico Susatyo Avatar answered Apr 14 '26 19:04

Enrico Susatyo


You are running into a bizarre feature of C that has propagated through its variants: the [mostly] equivalence of pointers and arrays.

if you do

int *sequence ; 

then you can do

sequence [4] ;

or

*(sequence + 4)

Arrays and points are mostly interchangeable. Arrays in C variants are merely data allocation. Your definition of

- (void)setLights:(int *)sequence 

conveys no information array information. You can still access sequence as though it is an array. setLights simply has no intrinsic information as to how many elements sequence has allocated to it.

The problem here is that your usage of the array in setLights needs to match how you have allotted the data.

If you did

sequence [100] = 10 ;

it would be syntactically correct but likely to create an error.

like image 25
user3344003 Avatar answered Apr 14 '26 21:04

user3344003



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!