PDA

View Full Version : Initializing C-style array for use in Objective-C class




Thethuthinang
Jan 28, 2012, 03:36 PM
I have some arrays that I need to initialize and use repeatedly throughout a class. For example:

float cubeMaterialDiffusion[] = {0.3, 0.7, 0.3, 1.0};

For the appropriate scope I need to declare the pointer to the array in the interface. However, if I declare cubeMaterialDiffusion in the interface as:

float* cubeMaterialDiffusion;

then I know of no concise way to initialize the array. I could do:

cubeMaterialDiffusion = malloc(4*sizeof(float));
cubeMaterialDiffusion[0] = 0.3;
cubeMaterialDiffusion[1] = 0.7;
cubeMaterialDiffusion[2] = 0.3;
cubeMaterialDiffusion[3] = 1.0;

Is there a better way to do this?



Sydde
Jan 28, 2012, 05:42 PM
I have not tried this, not really my style, what happens if you declare the ivar
float cubeMaterialDiffusion[4];
does it allocated the space for your array within your object? If so, if you expect to use an array that will not vary in size, then you can provide the pointer using the address operator '&' (it seems like poor style to me, but that is just me).

chown33
Jan 28, 2012, 05:59 PM
Is the same cubeMaterialDiffusion array used for all instances of the class? If so, then use a static C array, defined outside the @interface. Put it in the @implementation file, and declare it as a static array:
static float cubeMaterialDiffusion[] = {0.3, 0.7, 0.3, 1.0};

If you don't know why I'm using static, you should look it up in a C reference.

You might want the const qualifier on there, too, assuming the array is read-only.


If you need a different cubeMaterialDiffusion array for each instance, then it's like Sydde showed:
@interface YourClassName : YourSuperClass
{
float cubeMaterialDiffusion[4];
..etc..
@end

You don't get to use the concise initializer notation, so in your init method:
cubeMaterialDiffusion[0] = 0.3;
cubeMaterialDiffusion[1] = 0.7;
cubeMaterialDiffusion[2] = 0.3;
cubeMaterialDiffusion[3] = 1.0;

This is the same as every other use of an instance variable. You don't get concise initializers for any of them. The +alloc method guarantees that all ivars are zeroed. Any other initialization is your responsibility.

Thethuthinang
Jan 29, 2012, 12:56 PM
Thanks for the help.