Wesley Smith
Wesley Smith

Reputation: 19571

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

Upvotes: 3

Views: 657

Answers (3)

thxou
thxou

Reputation: 691

Is verbose only if you want. Use literals instead:

NSArray *sequence = @[@0, @1, @2, @3, @4, @5];

And access to the value like this:

UIImageView *light = lgtArray[[sequence[0] intValue]]];

Upvotes: 1

user3344003
user3344003

Reputation: 21617

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.

Upvotes: 1

Enrico Susatyo
Enrico Susatyo

Reputation: 19790

Use this syntax to pass the array:

- (void)setLights:(int[] )sequence

Upvotes: 2

Related Questions