views:

5487

answers:

3

In Java, it would look like this:

class Foo
{
  float[] array;
}

Foo instance = new Foo();
instance.array = new float[10];
+4  A: 

You can just use a pointer:

float *array;
// Allocate 10 floats -- always remember to multiple by the object size
// when calling malloc
array = (float *)malloc(10 * sizeof(float));
...
// Deallocate array -- don't forget to do this when you're done with your object
free(array);

If you're using Objective-C++, you could instead do:

float *array;
array = new float[10];
...
delete [] array;
Adam Rosenfield
+3  A: 

Here's another way to do it. Create a NSMutableArray object and add NSNumber objects to it. It's up to you to decide whether or not this is sensible.

NSMutableArray *array;
array = [[NSMutableArray alloc] init];
[array addObject:[NSNumber numberWithFloat:1.0f]];
[array release];
Chris Lundie
I guess there would be a performance penalty in not using the primitive float type.Also, using a mutable array when the required dimension is known in advance (and is not going to change) seems to be overkill.
Ariel Malka
Chris Lundie
You can initialize a mutable array with a specific size, even if that's known ahead of time you may still want a mutable array if you do not want to add all items to the array in one place.There is a performance concern but generally it's much better than the danger of using malloc wrongly.
Kendall Helmstetter Gelner
+3  A: 

Another way to do this in Objective-C is to use indexed instance variables:

@interface ArrayOfFloats : NSObject {
@private
  NSUInteger count;
  float      numbers[0];
}
+ (id)arrayOfFloats:(float *)numbers count:(NSUInteger)count;
- (float)floatAtIndex:(NSUInteger)index;
- (void)setFloat:(float)value atIndex:(NSUInteger)index;
@end

@implementation ArrayOfFloats
+ (id)arrayOfFloats:(float *)numbers count:(NSUInteger)count {
    ArrayOfFloats *result = [NSAllocateObject([self class], count * sizeof(float), NULL) init];
    if (result) {
        result->count = count;
        memcpy(result->numbers, numbers, count * sizeof(float));
    }
    return result;
}
...
@end

For more see the documentation for NSAllocateObject(). A limitation of indexed instance variables is that you can't subclass a class that uses them.

pcbeard
+1, I've never seen this explained before, thanks.
Rob Keniger