当维度在类实例化时未定义时,如何在 Objective-C 中将浮点数组声明为类变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/405426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 21:01:19  来源:igfitidea点击:

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

iphoneobjective-c

提问by Ariel Malka

In Java, it would look like this:

在 Java 中,它看起来像这样:

class Foo
{
  float[] array;
}

Foo instance = new Foo();
instance.array = new float[10];

回答by Adam Rosenfield

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:

如果您使用的是 Objective-C++,则可以改为:

float *array;
array = new float[10];
...
delete [] array;

回答by Chris Lundie

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 对象并向其添加 NSNumber 对象。这是否合理由您来决定。

NSMutableArray *array;
array = [[NSMutableArray alloc] init];
[array addObject:[NSNumber numberWithFloat:1.0f]];
[array release];

回答by pcbeard

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

在 Objective-C 中执行此操作的另一种方法是使用索引实例变量:

@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.

有关更多信息,请参阅NSAllocateObject()的文档。索引实例变量的一个限制是你不能对使用它们的类进行子类化。