How to declare an array of floats as a class variable in Objective-C when the dimension is undefined at the class instantiation time?

前端 未结 3 461
渐次进展
渐次进展 2021-02-11 04:33

In Java, it would look like this:

class Foo
{
  float[] array;
}

Foo instance = new Foo();
instance.array = new float[10];
3条回答
  •  生来不讨喜
    2021-02-11 05:15

    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.

提交回复
热议问题