我如何定义未指定大小的C数组,如在Objective-C的实例变量 [英] How can I define a C array of unspecified size, as an instance variable in Objective-C

查看:160
本文介绍了我如何定义未指定大小的C数组,如在Objective-C的实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Objective-C,我该怎么定义'未知大小作为一个实例变量的C数组,后来填充数组?

In Objective-C, how can I define a C array of 'unknown size' as an instance variable, and later populate the array?

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

(Background) : I have a class in Objective-C which handles loading game data. The data is stored in an array of C structs, contained in an external datafile. I can load in the array and access it, but I need it to be accessible throughout the class. What I'm trying to do is declare an 'empty' array in my instance variables and then (when loaded) point this empty array or replace it with the one I've loaded in.

这是如何我在加载我的数据...

This is how I'm loading in my data...

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);

所以这code工作正常重现我的阵列的 frame2d 的结构 - 我只需要知道我可以用这个作为一个实例变量

So this code works fine to recreate my array of frame2d structs - I just need to know how I can use this as an instance variable.

任何帮助是AP preciated,
谢谢。

Any help is appreciated, thanks.

推荐答案

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

Declare it as frame2d*, then figure out how big it needs to be at runtime and initialize it with calloc(numberOfFrame2Ds, sizeof(frame2d));

或者使用一个NSMutableArray,敷在NSValue的结构调整是否在运行时安全性比效率更重要的对象。

Or use an NSMutableArray and wrap the structs in NSValue objects if resizing and safety at runtime is more important than efficiency.

这篇关于我如何定义未指定大小的C数组,如在Objective-C的实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆