如何定义未指定大小的C数组,作为Objective-C中的实例变量

在Objective-C中,如何将“未知大小”的C数组定义为实例变量,然后填充数组?

(背景) :我在Objective-C中有一个类来处理加载游戏数据。 数据存储在C结构数组中,包含在外部数据文件中。 我可以加载数组并访问它,但我需要它可以在整个类中访问。 我要做的是在我的实例变量中声明一个’empty’数组然后(加载时)指向这个空数组或用我加载的数组替换它。

这就是我在我的数据中加载的方式……

FILE *fptr = NULL; fptr = fopen([path cStringUsingEncoding:NSUTF8StringEncoding], "r"); // Create an empty array of structs for the input file with known size frame2d newAnimationData[28]; // Read in array of structs fread(&newAnimationData, sizeof(newAnimationData), 1, fptr); fclose(fptr); 

所以这段代码可以很好地重新创建我的frame2d结构数组 – 我只需要知道如何将它用作实例变量。

任何帮助表示赞赏,谢谢。

将其声明为frame2d *,然后计算出它在运行时需要多大并用calloc初始化它(numberOfFrame2Ds,sizeof(frame2d));

或者使用NSMutableArray并在NSValue对象中包含结构,如果在运行时resize和安全性比效率更重要。

使用指向frame2d对象的指针作为实例变量:

 frame2D *animationData; 

您需要使用malloc在运行时分配数组。

如果整个文件只是框架,只需将其读入NSData对象:

 // in the interface @interface MyClass { NSData *animationData; frame2D *animationFrames; } // in the implementation animationData = [[NSData alloc] initWithContentsOfFile:path]; animationFrames = (frame2D*) [myData bytes]; -(void) dealloc { [animationData release]; } 

当你说你需要加载的数据“可以在整个类中访问”时,听起来你只需要一个你希望该类的所有对象都使用的数组。 如果是这样,请忘记实例变量。 您可以公开全局frame2d *并让您的对象访问:

 // Class.h extern frame2d *gClassFrames; // Class.m frame2d *gClassFrames; /* Somewhere in the class, read in the data and point `gClassFrames` at it. * If the array is actually of known size, just declare the entire array rather * than a pointer and read the data into that static storage, in order to avoid * dynamic memory allocation.*/ 

仅仅因为你正在编写Obj-C并不意味着你必须扔掉在C中工作正常的所有东西。让每个对象存储指向同一个数组的指针会浪费内存。

如果你想要一种更加客观的方式来获取信息,你可以添加一个类方法来访问它,无论是+ (frame2d *)frames还是+ (frame2d *)frameAtIndex:(NSUInteger)u