tags:

views:

43

answers:

2

I was checking out this question which has this code

- (NSArray *) percentagesRGBArray:(float[]) rgbArray
{
    NSNumber *red = [NSNumber numberWithFloat:rgbArray[0] / 255];
    NSNumber *green = [NSNumber numberWithFloat:rgbArray[1] / 255];
    NSNumber *blue = [NSNumber numberWithFloat:rgbArray[2] / 255];
    NSNumber *alpha = [NSNumber numberWithFloat:rgbArray[3]];
    return [NSArray arrayWithObjects:red, green, blue, alpha, nil];
}

and I thought, "that's terrible, what if you have more than three colors?" I know, you don't, but what if you did have count-1 colors and an alpha? Let's say you had [rgbArray count] (does count even work for a real array?) Using only objective-C, what the normal way that you would return an NSArray of n objects?

I just tried to work it out but I still don't have the chops to do this in objective-C. Here's my failed attempt:

- (NSArray *) what:(float[]) rgbArray
{
    int len = sizeof(rgbArray)/sizeof(float); // made up syntax
    NSLog(@"length is wrong dummy %d", len);
    NSNumber *retVal[len];
    for (int i=0;i<(len-1);i++) {
        NSNumber *red = [NSNumber numberWithFloat:rgbArray[0] / 255];
        retVal[i] = red;
        [red release];
    }
    retVal[len-1] = [NSNumber numberWithFloat:rgbArray[len-1]];
    return [NSArray arrayWithObjects:retVal count:len];

}
+5  A: 

You can use an NSMutableArray.

You can add & remove items from it and it is a subclass of NSArray so it can be passed to any method expecting an NSArray.

Ferruccio
+1  A: 

Well, just as arrayWithObjects:count: has count: part, you can do

- (NSArray *) what:(float[]) rgbArray count:(int)len
{
    NSMutableArray*result=[NSMutableArray array];
    for (int i=0;i<len;i++) {
        NSNumber *red = [NSNumber numberWithFloat:rgbArray[0] / 255];
        [result addObject:red];
    }
    return result;
}

If you want, I can be as close as what you wrote, which would be

- (NSArray *) what:(float[]) rgbArray count:(int)len
{
    NSNumber**retVal=malloc(len*sizeof(NSNumber*));
    for (int i=0;i<len;i++) {
        NSNumber *red = [NSNumber numberWithFloat:rgbArray[0] / 255];
        retVal[i]=red;
    }
    NSArray*result=[NSArray arrayWithObjects:retVal count:len];
    free(retVal);
    return result;
}

At this stage, it's not really a question of Objective-C, but is a question of just plain C, right? Your questions are

  1. how to dynamically allocate an array in C and
  2. how to get the size of an array from a function in C.

The answers are

  1. You use malloc.
  2. You can't do that, so you need to pass that to the function.

That's it. So, if you have a question about how to deal with C arrays, you should ask C experts... there's nothing special about Objective-C, except the method declaration syntax.

Yuji
Very cool. Now that I see your code I see the lack of precision in my question. I'll test some of this stuff back and comment back if I have any doubts. Thanks!
Yar